Spring 请求映射 + 参数绑定 完全攻略(2025 最新最全版)
这篇文章直接干掉 90% 的面试题 + 99% 的日常踩坑场景,全部基于 Spring Boot 3.x(Spring 6 大版本)真实生产写法。
一、请求映射全家桶(@RequestMapping 及其子注解)
| 注解 | HTTP 方法 | 推荐写法(2025) | 说明 |
|---|---|---|---|
| @GetMapping | GET | @GetMapping(“/users/{id}”) | 查询 |
| @PostMapping | POST | @PostMapping(“/users”) | 新增 |
| @PutMapping | PUT | @PutMapping(“/users/{id}”) | 全量更新 |
| @DeleteMapping | DELETE | @DeleteMapping(“/users/{id}”) | 删除 |
| @PatchMapping | PATCH | @PatchMapping(“/users/{id}”) | 部分更新 |
| @RequestMapping | 任意 | @RequestMapping(value = “/users”, method = “/users”, method = RequestMethod.GET) | 老项目或同时支持多种方法时使用 |
高级用法(常被问到)
@RestController
@RequestMapping("/api/v1")
public class UserController {
// 1. 多路径映射
@GetMapping({"/users", "/members", "/customers"})
public List<User> list() { ... }
// 2. Ant 风格路径
@GetMapping("/users/**") // 匹配 /users/a/b/c
@GetMapping("/users/*.jpg") // 匹配 .jpg 结尾
@GetMapping("/users/{id:[0-9]+}") // 正则:id 只能是数字
// 3. 同时支持 GET 和 POST(登录常见)
@RequestMapping(value = "/login", method = {RequestMethod.GET, RequestMethod.POST})
// 4. 带 headers、params、consumes、produces 条件映射
@GetMapping(value = "/users",
headers = "X-API-VERSION=1",
params = "type=admin",
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public List<User> listAdmin() { ... }
}
二、路径变量 @PathVariable(最容易出错的地方)
// 基本用法
@GetMapping("/users/{id}")
public User get(@PathVariable Long id) { ... }
// 多路径变量
@GetMapping("/orders/{orderId}/items/{itemId}")
public Item getItem(@PathVariable("orderId") Long orderId,
@PathVariable Long itemId) { ... }
// 可选路径变量(Spring Boot 3.2+ 支持)
@GetMapping({"/users", "/users/{id}"})
public User get(@PathVariable @PathVariable(required = false) Long id) {
return id == null ? userService.listAll() : userService.get(id);
}
// 使用 Map 接收所有路径变量(神技)
@GetMapping("/reports/{year}/{month}")
public String report(@PathVariable Map<String, String> pathVars) {
String year = pathVars.get("year");
String month = pathVars.get("month");
...
}
三、请求参数 @RequestParam(最常用的 10 种写法)
@GetMapping("/search")
public List<User> search(
// 1. 必填
@RequestParam String name,
// 2. 可选 + 默认值(最常用!)
@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "10") int size,
// 3. 参数名和变量名不一致
@RequestParam("userAge") Integer age,
// 4. 数组
@RequestParam List<Long> ids,
// 5. 多值参数(checkbox)
@RequestParam("hobby") List<String> hobbies,
// 6. 使用 Map 接收所有参数(调试神器
@RequestParam Map<String, String> allParams,
// 7. 日期类型自动转换(推荐)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
@RequestParam LocalDate startDate,
// 8. 必填校验(否则 400)
@RequestParam(required = true) String keyword
) { ... }
四、请求体 @RequestBody(JSON → Java 对象)
// 单个对象
@PostMapping("/users")
public User create(@RequestBody User user) { ... }
// 必须加 @Valid 做校验
@PostMapping("/users")
public R<User> create(@Valid @RequestBody UserCreateDTO dto) { ... }
// 批量
@PostMapping("/batch")
public List<User> batch(@RequestBody List<User> users) { ... }
// 泛型包装(推荐)
@PostMapping("/users")
public R<User> create(@RequestBody @Valid JsonWrapper<UserCreateDTO> wrapper) {
UserCreateDTO dto = wrapper.getData();
...
}
五、表单提交 @ModelAttribute(传统表单、复杂对象绑定)
// 1. 简单表单
@PostMapping("/register")
public String register(@ModelAttribute User user) { ... }
// 2. 嵌套对象绑定(神级用法)
public class OrderDTO {
private Long userId;
private List<OrderItem> items;
private Address shippingAddress;
}
// 前端传:items[0].productId=1 & items[0].quantity=2 & shippingAddress.province=北京
@PostMapping("/orders")
public Order create(@ModelAttribute @Valid OrderDTO order) { ... }
// 3. 绑定到 Model(自动加到模板)
@ModelAttribute("currentUser")
public User loadUser(Principal principal) {
return userService.getCurrent();
}
六、混合参数写法(真实项目中最常见)
@PatchMapping("/users/{id}")
public User update(@PathVariable Long id,
@RequestParam(required = false) String name,
@RequestParam(required = false) Integer age,
@RequestPart(value = "avatar", required = false) MultipartFile avatar) {
// 只更新传了的字段
...
}
七、文件上传三种写法(2025 最新推荐)
// 1. 单个文件
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file) { ... }
// 2. 多个文件
@PostMapping("/upload")
public String upload(@RequestParam("files") MultipartFile[] files) { ... }
// 3. 文件 + 其他参数(最常用)
@PostMapping("/article")
public String publish(@RequestPart("cover") MultipartFile cover,
@RequestPart("content") String content,
@RequestParam String title) { ... }
八、2025 年生产级最佳实践总结
| 场景 | 推荐写法 | 说明 |
|---|---|---|
| RESTful API | 全用 @RestController + @XXXMapping | 标准统一 |
| 路径变量 | @PathVariable Long id | 不要用基本类型防止 400 |
| 查询参数 | @RequestParam + defaultValue | 必配默认值 |
| 分页 | 用 Pageable(Spring Data 神器) | |
| JSON 请求体 | @Valid @RequestBody DTO | 强制校验 |
| 表单提交 | @ModelAttribute + @Valid | |
| 文件上传 | @RequestPart | 支持 Swagger 文档更好 |
| 统一响应 | ResponseEntity> 或自定义 R |
九、Pageable 分页神器(所有项目必用)
@GetMapping("/users")
public Page<User> list(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size,
@RequestParam(defaultValue = "id,desc") String sort) {
// 推荐写法(最优雅)
@PageableDefault(size = 20, sort = "createTime", direction = Sort.Direction.DESC)
Pageable pageable
) {
return userService.page(pageable);
}
现在你已经完全掌握 Spring 请求映射与参数绑定的全部姿势了!
这些写法直接复制到项目里,绝对稳、绝对优雅、绝对不会被面试官问倒。
下一步想学什么?
- Spring 参数校验全套(@Valid + 全局异常 + 分组校验 + 自定义校验器)
- 全局统一响应 + 枚举码设计
- Swagger 3 (OpenAPI) 最新配置
- Spring Security + JWT 权限控制
- 控制器单元测试 @WebMvcTest 完整示例
直接说,我继续给你写 10 万字级别的实战教程!