Web 控制层(接收请求、参数解析)
专门处理前端 HTTP 请求,负责路径映射、参数接收、响应结果(JSON 为主),是前后端交互的核心层。
| 注解 | 作用说明 |
|---|---|
@RestController |
整合 @Controller(标记控制器)和 @ResponseBody(返回 JSON 格式),无需单独加 @ResponseBody |
@GetMapping |
专门处理 GET 请求,简化 @RequestMapping(method = RequestMethod.GET) |
@PostMapping |
专门处理 POST 请求,简化 @RequestMapping(method = RequestMethod.POST) |
@PathVariable |
接收 URL 路径中的参数(如 /user/1 中的 1),需配合路径占位符使用 |
@RequestParam |
接收 URL 查询参数(如 /user?name=张三)或表单参数,支持设置默认值 |
@RequestBody |
接收前端传递的 JSON 格式请求体,自动将 JSON 转换为 Java 对象 |
// 控制器核心注解:@RestController
@RestController
// 通用路径映射:所有接口都以 /user 开头
@RequestMapping("/user")
public class UserController {
// 1. GET 请求 + 路径参数(@GetMapping + @PathVariable)
@GetMapping("/{id}")
public String getUserById(@PathVariable Long id) {
// 接收路径中的 id 参数(如 /user/123)
return "查询到用户ID:" + id;
}
// 2. GET 请求 + 查询参数(@GetMapping + @RequestParam)
@GetMapping("/search")
public String searchUser(
// 接收查询参数 name,默认值为 "未知用户"
@RequestParam(defaultValue = "未知用户") String name,
// 接收查询参数 age,非必填
@RequestParam(required = false) Integer age
) {
return "查询条件:姓名=" + name + ",年龄=" + (age == null ? "未填写" : age);
}
// 3. POST 请求 + JSON 请求体(@PostMapping + @RequestBody)
@PostMapping("/add")
public User addUser(@RequestBody User user) {
// 接收前端传递的 JSON 对象,自动转换为 User 实体
System.out.println("新增用户:" + user.getUsername());
return user; // 返回 JSON 格式的新增结果
}
}
// 实体类(配合 @RequestBody 使用)
@Data // Lombok 注解,简化 getter/setter(后续会讲)
public class User {
private Long id;
private String username;
private Integer age;
}