Spring:@RequestMapping
RequestMapping 是 Spring MVC 框架中最核心的注解之一用于将 HTTP 请求映射到控制器Controller中的处理方法实现请求路由功能。基本作用建立 URL 路径 与 控制器方法 之间的映射关系。可标注在 类级别定义公共路径前缀或 方法级别定义具体请求路径。常用属性属性 类型 说明value / path String[] 指定请求路径支持多个路径如 /user, /api/usermethod RequestMethod[] 指定支持的 HTTP 方法如 GET, POSTparams String[] 限定请求必须包含特定参数如 usernameadminheaders String[] 限定请求必须包含特定请求头如 Content-Typeapplication/jsonconsumes String[] 限定请求的内容类型如 application/jsonproduces 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 方法时优先使用派生注解语义更清晰、代码更简洁。组合使用示例RestControllerRequestMapping(/api/users) //类级别公共前缀public class UserController {GetMapping(/{id}) // 方法级别/api/users/123public User getUser(PathVariable Long id) {return userService.findById(id);}PostMapping // /api/userspublic 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/123zwnj;**匹配任意多层路径如 /user/**zwnj; 匹配 /user/123/profile注意事项默认支持所有 HTTP 方法若未指定 method则该方法响应所有请求方式GET、POST、PUT 等。避免映射冲突同一路径方法组合不能重复映射到多个方法否则启动报错 Ambiguous mapping。类路径 方法路径 最终访问路径如类上 /api方法上 /user则完整路径为 /api/user。