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。
相关推荐
菜鸟谢1 分钟前
Rust 智能指针完整详解
后端
菜鸟谢12 分钟前
Rust 函数完整知识点详解
后端
爱勇宝22 分钟前
淡泊名利之前,先承认我们都很焦虑
前端·后端·程序员
菜鸟谢25 分钟前
Rust 闭包(Closure)完整详解
后端
ServBay28 分钟前
如何利用本地技术栈构建 0 成本 AI SaaS 雏形
后端·aigc·ai编程
菜鸟谢29 分钟前
Rust 集合 + 迭代器完整详解
后端
杨利杰YJlio32 分钟前
Codex桌面客户端上手:项目、插件与自动化实战
前端·后端
常铭37 分钟前
【Java基础】01-HashMap的底层原理
后端·面试
幼儿园技术家1 小时前
实现 GEO 监控:从多引擎探测到优化闭环
前端·后端
掘金者阿豪1 小时前
微信小程序虚拟支付与广告转化回传实战记录
后端