Spring:@RequestMapping

@RequestMapping 是 Spring MVC 框架中最核心的注解之一,用于将 ‌HTTP 请求映射到控制器(Controller)中的处理方法‌,实现请求路由功能。
‌基本作用‌

建立 ‌URL 路径‌ 与 ‌控制器方法‌ 之间的映射关系。

可标注在 ‌类级别‌(定义公共路径前缀)或 ‌方法级别‌(定义具体请求路径)。

常用属性‌

属性 类型 说明

value / path String\[\] 指定请求路径,支持多个路径(如 "/user", "/api/user")

method RequestMethod\[\] 指定支持的 HTTP 方法(如 GET, POST)

params String\[\] 限定请求必须包含特定参数(如 "username=admin")

headers String\[\] 限定请求必须包含特定请求头(如 "Content-Type=application/json")

consumes String\[\] 限定请求的内容类型(如 application/json)

produces String\[\] 限定响应的内容类型(如 application/xml)

示例:

@RequestMapping(value = "/user", method = RequestMethod.GET)

等价于 @GetMapping("/user")

‌派生注解(推荐使用)‌

为提升代码可读性,Spring 提供了针对常用 HTTP 方法的简化注解:

@GetMapping → @RequestMapping(method = GET)

@PostMapping → @RequestMapping(method = POST)

@PutMapping → @RequestMapping(method = PUT)

@DeleteMapping → @RequestMapping(method = DELETE)

@PatchMapping → @RequestMapping(method = PATCH)

推荐场景:当接口仅支持一种 HTTP 方法时,优先使用派生注解,语义更清晰、代码更简洁

‌组合使用示例‌

@RestController

@RequestMapping("/api/users") // 类级别:公共前缀

public class UserController {

@GetMapping("/{id}") // 方法级别:/api/users/123

public User getUser(@PathVariable Long id) {

return userService.findById(id);

}

@PostMapping // /api/users

public User createUser(@RequestBody User user) {

return userService.save(user);

}

@RequestMapping(value = "/multi", method = {RequestMethod.GET, RequestMethod.POST})

public String multiMethod() {

return "支持 GET 和 POST";

}

}

‌路径变量与通配符‌

‌路径变量‌:使用 {} 定义变量,配合 @PathVariable 获取值

@GetMapping("/user/{id}")

public String getUser(@PathVariable("id") Long userId) { ... }

‌Ant 风格通配符‌:

*:匹配任意单个路径段(如 /user/* 匹配 /user/123)

‌**:匹配任意多层路径(如 /user/**‌ 匹配 /user/123/profile)

‌注意事项‌

  • ‌默认支持所有 HTTP 方法‌:若未指定 method,则该方法响应所有请求方式(GET、POST、PUT 等)。
  • ‌避免映射冲突‌:同一路径+方法组合不能重复映射到多个方法,否则启动报错 Ambiguous mapping。
  • ‌类路径 + 方法路径 = 最终访问路径‌:如类上 /api,方法上 /user,则完整路径为 /api/user。
相关推荐
卓怡学长10 分钟前
w176基于SpringBoot的医院管理系统
java·spring boot·spring·maven·intellij-idea
lemon_sjdk10 分钟前
ObjectProperty
java·开发语言·算法
大模型码小白16 分钟前
Spring AI Tool 实现自然语言操作 MySQL 数据库详解
服务器·开发语言·数据库·人工智能·python·mysql·spring
hh95020 分钟前
Agent Plan x DeepSeek Harness:Agent 供应链安全与第三方插件审计
java·开发语言·安全·agent plan·adg成都社区·adg社区
吴声子夜歌27 分钟前
Java面试——HBase原理及应用
java·面试·hbase
浪兎兎32 分钟前
【Java Web】Servlet + JSP 笔记
java·前端·servlet
吴声子夜歌1 小时前
Java面试——ElasticSearch原理及应用
java·面试·es
lhldsg1 小时前
家政派单系统开发实战:从需求分析到智能调度全流程指南
java·junit·小程序·uni-app·需求分析
吴声子夜歌1 小时前
Java面试——Spring原理及应用(一)
java·spring·面试
灰阳阳1 小时前
Docker-数据卷命令解析
java·docker·eureka