@requestmapping 是 spring mvc 最基础的请求映射注解,支持路径与 http 方法限定;推荐使用语义更清晰的派生注解如 @getmapping、@postmapping 等,它们是其快捷封装,且支持 ant 风格路径和 uri 变量,方法不匹配时返回 405 错误。

在 Spring MVC 中,@RequestMapping 是最基础的请求映射注解,它既能指定 URL 路径,也能限定 HTTP 请求方法(如 GET、POST)。不过更推荐使用语义更清晰的派生注解(如 @GetMapping、@PostMapping),它们本质是 @RequestMapping 的快捷封装。
用 @RequestMapping 指定路径和请求方法
直接在控制器方法上使用 @RequestMapping,通过 value(或简写为默认属性)设置路径,用 method 参数指定允许的 HTTP 方法:
-
@RequestMapping(value = "/login", method = RequestMethod.GET)→ 只响应 GET /login -
@RequestMapping(value = "/login", method = RequestMethod.POST)→ 只响应 POST /login - 可同时支持多个方法:
method = {RequestMethod.GET, RequestMethod.POST}
更简洁的写法:使用 @GetMapping、@PostMapping 等
Spring 4.3+ 提供了更直观的注解,语义明确、代码更易读:
-
@GetMapping("/user")等价于@RequestMapping(value = "/user", method = RequestMethod.GET) -
@PostMapping("/user")等价于@RequestMapping(value = "/user", method = RequestMethod.POST) - 还有
@PutMapping、@DeleteMapping、@PatchMapping
路径匹配与占位符支持
@RequestMapping 和派生注解都支持 Ant 风格路径和 URI 变量:
-
@GetMapping("/users/{id}")→ 匹配/users/123,用@PathVariable("id")获取值 -
@RequestMapping("/api/**")→ 匹配所有以/api/开头的路径 -
@GetMapping("/users/*/profile")→ 匹配/users/abc/profile、/users/123/profile
注意点:方法限定是强约束
如果请求方法不匹配(比如用 GET 访问只声明了 @PostMapping 的接口),Spring MVC 会返回 405 Method Not Allowed 错误,而不是 404。这说明路径能匹配上,但方法被拒绝。
- 确保前端发起的请求方法与后端声明一致
- 表单默认是 GET,如需 POST,记得设
<form method="post"></form> - REST 客户端(如 curl、Postman)要手动选择请求方法
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











