Spring @RequestMapping 注解详解
@RequestMapping
是 Spring MVC 中 定义请求映射规则的核心注解,用于将 HTTP 请求映射到 Controller 处理方法。以下通过场景化解释其功能、参数及使用技巧:
一、核心作用
-
URL 路径映射
将特定 URL 请求路由到对应的 Controller 方法。<JAVA>
@Controller @RequestMapping("/user") // 类级别路径,所有方法路径前添加 /user public class UserController { @RequestMapping("/profile") // 完整路径:/user/profile public String profile() { return "user/profile"; } }
-
支持多种HTTP方法
通过method
参数限定请求方法(GET、POST等)。<JAVA>
@RequestMapping(value = "/create", method = RequestMethod.POST) public String createUser(User user) { userService.save(user); return "redirect:/user/list"; }
-
多请求处理
支持同时响应多个 URL 路径或请求参数。<JAVA>
@RequestMapping(value = {"/list", "/all"}, method = RequestMethod.GET) public String listUsers(Model model) { model.addAttribute("users", userService.findAll()); return "user/list"; }
二、关键参数说明
参数 | 作用描述 | 示例 |
---|---|---|
value / path | 指定映射的URL路径(可多路径) | @RequestMapping("/api/user") |
method | 限制HTTP请求方法(GET、POST等) | method = RequestMethod.PUT |
params | 要求请求必须包含特定参数 | params = "type=admin" (参数须为 type=admin ) |
headers | 限制请求头条件 | headers = "Content-Type=application/json" |
consumes | 指定处理的请求内容类型(Content-Type) | consumes = MediaType.APPLICATION_JSON_VALUE |
produces | 指定响应内容的类型(Accept头匹配) | produces = "text/plain;charset=UTF-8" |
三、快捷组合注解
Spring 4.3+ 提供简化的HTTP方法注解,替代 method
参数配置:
@GetMapping
→@RequestMapping(method = GET)
@PostMapping
→@RequestMapping(method = POST)
@PutMapping
、@DeleteMapping
、@PatchMapping
用法示例:
<JAVA>
@RestController
@RequestMapping("/api/v1")
public class UserApiController {
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
return userService.findById(id);
}
@PostMapping("/users")
public ResponseEntity<?> createUser(@RequestBody User user) {
userService.save(user);
return ResponseEntity.created(URI.create("/users/" + user.getId())).build();
}
}
四、动态路径参数(@PathVariable
)
通过 {变量名}
语法捕获 URL 路径中的动态值,搭配 @PathVariable
使用:
<JAVA>
@GetMapping("/detail/{userId}/{type}")
public String userDetail(
@PathVariable("userId") Long id,
@PathVariable String type // 变量名相同可省略参数
) {
// 示例URL:/user/detail/123/admin
// id=123, type="admin"
return "user/detail";
}
五、匹配请求参数(params
条件)
-
要求存在某个参数
<JAVA>
@RequestMapping(value = "/search", params = "keyword") public String searchByKeyword(String keyword) { ... }
-
参数值匹配指定模式
<JAVA>
@GetMapping(value = "/filter", params = "status=active") public List<User> getActiveUsers() { ... }
六、常见问题与解决
1. 路径冲突问题
- 问题:多个处理方法映射到同一路径导致冲突。
- 解决:通过
method
或params
进一步区分请求。<JAVA>
@GetMapping("/edit") public String editForm() { ... } @PostMapping("/edit") public String saveEdit(User user) { ... }
2. 模糊匹配优先问题
- 问题:
/user/*
和/user/123
同时存在时,优先匹配更具体的路径。 - 规则:Spring 优先匹配精确路径,再匹配通配符路径。
七、最佳实践
-
RESTful 风格设计
使用HTTP方法区分操作:GET
→ 查询资源POST
→ 新增资源PUT
→ 更新完整资源PATCH
→ 部分更新资源DELETE
→ 删除资源
-
显式指定 Content-Type
使用consumes
和produces
明确请求与响应格式:<JAVA>
@PostMapping(value = "/create", consumes = "application/json", produces = "application/json") public User createUserJson(@RequestBody User user) { ... }
-
推荐使用组合注解
优先用@GetMapping
、@PostMapping
,提升代码可读性。
八、其他特性
Ant风格通配符支持:
?
: 匹配单个字符*
: 匹配任意数量的字符(不包含路径分隔符)**
: 跨多级路径匹配(例如/api/**
匹配/api/users/123
)
<JAVA>
@GetMapping("/files/*.txt") // 匹配 /files/note.txt 或 /files/data.txt
public String handleTextFiles() { ... }
总结
- 核心定位:
@RequestMapping
是定义 HTTP 请求入口的关键注解。 - 简化开发:通过 组合注解 + PathVariable + 参数条件 实现 RESTful 接口。
- 注意点:确保路径唯一性,避免冲突;优先使用组合注解提升代码清晰度。