SpringBootWeb请求与响应
1. 请求
最原始的方式(了解):
对象: HttpServletRequest request
获取参数: String name = request.getParameter("name");
1). 简单参数:
xxx?name=Tom&age=10 ----------- String name , Integer age
规则: 请求参数名 与 方法形参名 保持一致 .
参数名不一致 :
xxx?username=Tom&age=10 ----------- @RequestParam("username") String name , Integer age
2). 实体类参数:
xxx?name=Tom&age=10 ------------- User user
规范: 参数名 与 实体类的属性名一致 .
3). 数组集合参数:
xxxxx?hobby=name&hobby=java&hobby=go -------------- String[] hobby
xxxxx?hobby=name&hobby=java&hobby=go -------------- @RequestParam List<String> hobby
4). 日期类型 : Date , LocalDateTime
xxxxx?updateTime=2022-08-30 14:20:30 --------------- @DateTimeFormat("yyyy-MM-dd HH:mm:ss") Date updateTime
xxxxx?updateTime=2022-08-30 14:20:30 --------------- @DateTimeFormat("yyyy-MM-dd HH:mm:ss") LocalDateTime updateTime
5). JSON 格式 :
POST 请求体: {
"name":"Tom", "age": 10} --------------------> @RequestBody User user
6). 路径参数
http://localhost:8080/path/1/2
@RequestMapping("/path/{id}/{status}")
public String path(@PathVariable Integer id , @PathVariable Integer status){
}
2. 响应
2.1 注解
@ReponseBody
如果响应的数据是一个简单类型: String , Integer , Double -----------> 直接响应回去
如果返回的数据是实体类 , List集合, Set 集合, Map ------------------> json格式
@RestController = @Controller , @ResponseBody
2.2 统一响应结果
不论开发的增删改查什么样的方法, 我们都统一给前端返回一个统一的结果 。
public class Result{
private Integer code;
private String msg;
private Object data;
}
3. 分层解耦
3.1 分层 (三层架构)
- Controller : 控制层,接收请求,返回响应
- Service : 业务层, 逻辑处理
- Dao:数据访问层,数据的操作, 数据的增删改查
流程:
浏览器 <----->> Controller <------->> Service <---------> >Dao <-------->> 文件 (数据库) .
3.2 解耦
耦合的代码 UserController:
private UserServiceA userServiceA = new UserServiceA();
解耦思路:
private UserService userService ;
- 对Service , Dao层对象交给 容器 管理 . ------------------------------> IOC : 控制反转 .
- Controller , Service运行时,依赖的资源从 容器 中获取 . -------------> DI : 依赖注入 .
3.3 IOC & DI
A. bean声明的注解
@Component
@Controller ------------------------> controller 层
@Service ----------------------------> service 层
@Repository -------------------------> dao 层
B. 组件扫描
注解 : @ComponentScan
引导类: @SpringBootApplication ------------> 包含了 @ComponentScan 默认扫描引导类所在包及其子包 .
C. 依赖注入
@Autowired : 默认类型进行注入
该类型下的bean有多个 :
@Primary
@Autowired + @Qualifier("xxxx")
@Resource(name="xxxx")
注解 :
@RestController : 加在Controller类上的 。
@RequestMapping("/hello") : 目前加在方法上 , value就是前端请求的路径 .
@RequestParam
A. 当前端传递的参数名 与 方法形参名不一致 . xxx?name=tom @RequestParam("name") String username
B. 封装List集合数据 ---------------------> xxx?hobby=name&hobby=java @RequestParam List<String> hobby
@DateTimeFormat : 日期对象封装时使用该注解指定日期格式
@PathVariable : 获取路径参数 .
@RequestBody ----------> 作用: json格式 ------> 对象
@ResponseBody ---------> 作用: 对象/集合 -----> json格式
@RestController = @Controller + @ResponseBody
@Component : 将类产生 对象, 交给 IOC 容器管理 . ------------> IOC容器管理的对象, 称为 bean
@Autowired (自动装配): 注入 , 默认安装类型进行注入