文章目录
- 1. Maven
- 1.1 IDEA集成Maven
- 1.2 依赖管理
- 1.2.1 依赖配置
- 1.2.2 排除依赖
- 1.2.3 生命周期
- 1.3 单元测试
- 1.3.1 概述
- 1.3.2 test
- 1.3.3 断言
- 1.3.4 常见注解
- 1.3.5 Maven依赖范围
- 1.3.6 maven常见问题
- 2. Web基础
- 2.1 SpringBoot Web入门
- 2.1.1 入门程序
- 2.1.2 HTTP协议
- 2.1.2.1 请求协议
- 2.1.2.2 响应协议
- 2.2 SpringBoot Web案例
- 2.3 分层解耦
- 2.3.1 三层架构
- 2.3.2 IOC与DI
1. Maven
1.1 IDEA集成Maven
1.2 依赖管理
1.2.1 依赖配置
可以去这个网站搜索我们需要配置的依赖的坐标
1.2.2 排除依赖
<!--配置依赖--><dependencies><!-- https://mvnrepository.com/artifact/org.springframework/spring-context --><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>6.1.4</version><!--排除依赖--><exclusions><exclusion><groupId>io.micrometer</groupId><artifactId>micrometer-observation</artifactId></exclusion></exclusions></dependency></dependencies>
1.2.3 生命周期
主要关注以下五个生命周期的阶段
同一套生命周期中,后面的阶段运行,前面的阶段都会运行
1.3 单元测试
1.3.1 概述
测试方法:白盒测试,黑盒测试,灰盒测试
1.3.2 test
- pom.xml文件中引入Junit依赖
- 在目录下创建test类,编写对应的测试方法,在方法上声明@test注解
- 运行
package com.itheima;
import org.junit.jupiter.api.Test;
public class UserServiceTest {
@Test
public void testGetAge(){
UserService userservice = new UserService();
Integer age = userservice.getAge("100000200001021234");
System.out.println(age);
}
}
package com.itheima;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
public class UserService {
/**
* 给定一个身份证号, 计算出该用户的年龄
* @param idCard 身份证号
*/
public Integer getAge(String idCard){
if (idCard == null || idCard.length() != 18) {
throw new IllegalArgumentException("无效的身份证号码");
}
String birthday = idCard.substring(6, 14);
LocalDate parse = LocalDate.parse(birthday, DateTimeFormatter.ofPattern("yyyyMMdd"));
return Period.between(parse, LocalDate.now()).getYears();
}
/**
* 给定一个身份证号, 计算出该用户的性别
* @param idCard 身份证号
*/
public String getGender(String idCard){
if (idCard == null || idCard.length() != 18) {
throw new IllegalArgumentException("无效的身份证号码");
}
return Integer.parseInt(idCard.substring(16,17)) % 2 == 1 ? "男" : "女";
}
}
1.3.3 断言
测试运行结果是绿色并不能说明代码没问题
使用断言判断期望得到的值是否和结果相同
package com.itheima;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class UserServiceTest {
@Test
public void testGetAge(){
UserService userservice = new UserService();
Integer age = userservice.getAge("100000200001021234");
System.out.println(age);
}
// @Test
// public void testGetGender(){
// UserService userservice = new UserService();
// String gender = userservice.getGender("100000200001021234");
// System.out.println(gender);
// }
// 断言
@Test
// public void testGenderWithAssert(){
// UserService userservice = new UserService();
// String gender = userservice.getGender("100000200001021234");
//// System.out.println(gender);
// //断言;
// Assertions.assertEquals("男",gender,"性别获取错误");
//}
public void testGenderWithAssert(){
UserService userservice = new UserService();
String gender = userservice.getGender("100000200001021234");
// System.out.println(gender);
//断言;
// Assertions.assertEquals("男",gender,"性别获取错误");
Assertions.assertThrows(IllegalArgumentException.class,()->{
userservice.getGender(null);
});
}
}
1.3.4 常见注解
package com.itheima;
import org.junit.jupiter.api.*;
public class UserServiceTest {
/**
* @BeforeAll //在所有的单元测试方法运行之前,运行一次
*/
@BeforeAll
public static void beforeAll(){
System.out.println("before All");
}
/**
* @AfterAll //在所有的单元测试方法运行之后,运行一次
*/
@AfterAll
public static void afterAll(){
System.out.println("after All");
}
/**
* @BeforeEach //在每一个单元测试方法运行之前,都会运行一次
*/
@BeforeEach
public void beforeEach(){
System.out.println("before Each");
}
/**
* @AfterEach //在每一个单元测试方法运行之后,都会运行一次
*/
@AfterEach
public void afterEach(){
System.out.println("after Each");
}
// 断言
@Test
public void testGetAge(){
UserService userservice = new UserService();
Integer age = userservice.getAge("100000200001021234");
System.out.println(age);
}
@Test //这里要是不写Test的话,测试的时候会忽视这个方法
public void testGenderWithAssert(){
UserService userservice = new UserService();
String gender = userservice.getGender("100000200001021234");
System.out.println(gender);
//断言;
// Assertions.assertEquals("男",gender,"性别获取错误");
Assertions.assertThrows(IllegalArgumentException.class,()->{
userservice.getGender(null);
});
}
/**
* 参数化测试
*/
@DisplayName("测试用户性别")
@ParameterizedTest
@ValueSource(strings = {"100000200010011011", "100000200010011031", "100000200010011051"})
public void testGetGender2(String idCard) {
UserService userService = new UserService();
String gender = userService.getGender(idCard);
// 断言
Assertions.assertEquals("男", gender);
}
}
1.3.5 Maven依赖范围
<!--Junit依赖--><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter</artifactId><version>5.9.1</version><scope>test</scope></dependency>
1.3.6 maven常见问题
2. Web基础
2.1 SpringBoot Web入门
2.1.1 入门程序
package com.itheima;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController//说明是一个请求处理类
public class HelloController {
@RequestMapping("/hello")
public String hello(String name)
{
System.out.println("name:"+name);
return "hello"+ name+"~";
}
}
连不上spring.io的话换阿里云
2.1.2 HTTP协议
2.1.2.1 请求协议
请求数据格式
请求数据获取
package com.itheima;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RequestController {
@RequestMapping("/request")
public String request(HttpServletRequest request) {
//1. 获取请求方式
String method = request.getMethod();
System.out.println("请求方式:"+ method);
//2.获取请求url地址
String url = request.getRequestURL().toString();
System.out.println("请求URL:"+ url);
// 获取uri
String uri = request.getRequestURI();
System.out.println("请求URI:"+ uri);
//3. 获取请求协议
String protocol = request.getProtocol();
System.out.println("请求协议:"+ protocol);
//4. 获取请求参数
String name = request.getParameter("name");
System.out.println("name:"+ name);
String age = request.getParameter("age");
System.out.println("age:"+ age);
//5. 获取请求头
String header = request.getHeader("Accept");
System.out.println("Accept:"+ header);
return "OK";
}
}
2.1.2.2 响应协议
重定向:浏览器向A发出请求,但是实际在B服务器,A会返回状态码和资源位置,浏览器会自动再次发出请求
200:处理成功
404:请求资源不存在
500:服务器发生不可预测的错误
响应数据设置:
package com.itheima;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
@RestController
public class ResponseController {
// 1. 设置HttpServletResponse响应数据
@RequestMapping("/response")
public void response(HttpServletResponse response) throws IOException{
// 1.设置响应状态码
response.setStatus(401);
// 2.设置响应头
response.setHeader("name","itheima");
// 3.设置响应体
response.getWriter().write("<h1>Hello Response</h1>");
}
// 2. 使用ResponseEntity对象封装响应数据
@RequestMapping("/response2")
public ResponseEntity<String> response2(){
return ResponseEntity.status(401).header("name","itheima").body("<h1>Hello Response</h1>");}}
2.2 SpringBoot Web案例
如果创建模块有问题可能是Lombok没加版本号的原因,也有可能是注解的原因,目前不知道为什么,别使用Lombok的注解,自己写getter setter方法
我的项目文件不能右键添加模块:文件->项目结构->选择左边模块->把目录xml文件添加进去
出现了创建不成功的情况,最后01改成02创建成功了
package com.itheima.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
@Data // 提供get set方法
@NoArgsConstructor // 无参构造
@AllArgsConstructor // 全参构造
public class user {
// id
private Integer id;
private String username;
private String password;
private String name;
private Integer age;
private LocalDateTime updateTime;;
}
package com.itheima.controller;
import cn.hutool.core.io.IoUtil;
import com.itheima.pojo.user;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
//import static jdk.internal.org.jline.utils.InfoCmp.Capability.lines;
@RestController
public class UserController {
@RequestMapping("/list")
public List<user> list() throws Exception {//1. 加载读取user.txt文件,获取用户数据// InputStream in = new FileInputStream("D:\\SoftWare\\JAVA\\project\\WebAI_Project\\web-ai-project-01\\springboot-web-0417\\src\\main\\resources\\user.txt");InputStream in = this.getClass().getClassLoader().getResourceAsStream("user.txt");ArrayList<String> lines = IoUtil.readLines(in, StandardCharsets.UTF_8, new ArrayList<>());//2. 解析用户信息,封装成user对象,封装为一个list集合List<user> userList =lines.stream().map(line -> {String[] parts = line.split(",");Integer id = Integer.parseInt(parts[0]);String username = parts[1];String password = parts[2];String name = parts[3];Integer age = Integer.parseInt(parts[4]);LocalDateTime updateTime = LocalDateTime.parse(parts[5], DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));return new user(id, username, password, name, age, updateTime);}).toList();//3. 返回数据(json)return userList;}}
2.3 分层解耦
2.3.1 三层架构
单一职责原则
2.3.2 IOC与DI
IOC详细解释:
DI详解:
存在多个相同类型的bean,代码会报错
package com.itheima.controller;
import cn.hutool.core.io.IoUtil;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
//import static jdk.internal.org.jline.utils.InfoCmp.Capability.lines;
@RestController
public class UserController {
// @RequestMapping("/list")
// public List<User> list() throws Exception {// //1. 加载读取user.txt文件,获取用户数据//// InputStream in = new FileInputStream("D:\\SoftWare\\JAVA\\project\\WebAI_Project\\web-ai-project-01\\springboot-web-0417\\src\\main\\resources\\user.txt");// InputStream in = this.getClass().getClassLoader().getResourceAsStream("user.txt");// ArrayList<String> lines = IoUtil.readLines(in, StandardCharsets.UTF_8, new ArrayList<>());////2. 解析用户信息,封装成user对象,封装为一个list集合// List<User> userList =lines.stream().map(line -> {// String[] parts = line.split(",");// Integer id = Integer.parseInt(parts[0]);// String username = parts[1];// String password = parts[2];// String name = parts[3];// Integer age = Integer.parseInt(parts[4]);// LocalDateTime updateTime = LocalDateTime.parse(parts[5], DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));// return new User(id, username, password, name, age, updateTime);// }).toList();//// //3. 返回数据(json)// return userList;// }// private UserService userService = new UserServiceImpl();//方式一. 属性注入// @Autowired// private UserService userService;//使用IOC和DI实现////方式二. 构造方法注入// private final UserService userService;// @Autowired // 如果当前类中只有一个构造函数,@Autowired可以省略// public UserController(UserService userService) {// this.userService = userService;// }//方式三. setter方法注入private UserService userService;@Qualifier("userServiceImpl")@Autowiredpublic void setUserService(UserService userService) {this.userService = userService;}@RequestMapping("/list")public List<User> list() {// 1. 调用service,获取数据List<User> userList = userService.findAll();return userList;// return userService.findAll();}}
package com.itheima.dao.impl;
import cn.hutool.core.io.IoUtil;
import com.itheima.dao.UserDao;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
//@Component //将当前类交给IOC容器处理
@Repository("userDao")
public class UserDaoImpl implements UserDao {
//1. 加载读取user.txt文件,获取用户数据
@Override
public List<String> findAll() {InputStream in = this.getClass().getClassLoader().getResourceAsStream("user.txt");ArrayList<String> lines = IoUtil.readLines(in, StandardCharsets.UTF_8, new ArrayList<>());return lines;}}
package com.itheima.service.impl;
import com.itheima.dao.UserDao;
import com.itheima.dao.impl.UserDaoImpl;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
//@Component
@Service
public class UserServiceImpl implements UserService {
@Autowired //应用程序运行时会自动查找该类型的bean对象,并赋值给该成员变量
private UserDao UserDao;
@Override
public List<User> findAll(){//1. 调用dao获取数据List<String> lines = UserDao.findAll();//2. 解析用户信息,封装成user对象,封装为一个list集合List<User> userList =lines.stream().map(line -> {String[] parts = line.split(",");Integer id = Integer.parseInt(parts[0]);String username = parts[1];String password = parts[2];String name = parts[3];Integer age = Integer.parseInt(parts[4]);LocalDateTime updateTime = LocalDateTime.parse(parts[5], DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));return new User(id, username, password, name, age, updateTime);}).toList();return userList;}}