@RequestMapping 是 Spring MVC 中用于绑定 HTTP 请求路径与处理方法的核心注解,既可标注在类上,也可标注在方法上。
- 类上使用:定义该控制器的公共父路径;
- 方法上使用:指定具体接口的路径和请求方式。
常用属性
| 属性 | 说明 |
value(或直接写路径) |
请求路径,如 "/user" |
method |
HTTP 方法,如 RequestMethod.GET |
produces |
响应内容类型,常用于指定 JSON 编码:produces = "application/json; charset=UTF-8" |
示例
@RestController @RequestMapping("/test") // 类级别路径前缀 public class TestController { @RequestMapping(value = "/get", method = RequestMethod.GET) public String testGet() { return "success"; } }
访问 http://localhost:8080/test/get 即可触发该方法。
更简洁的写法:专用映射注解
Spring 提供了针对不同 HTTP 方法的快捷注解,无需再写 method 属性:
| 快捷注解 | 等价于 |
@GetMapping("/path") |
@RequestMapping(method = GET) |
@PostMapping("/path") |
@RequestMapping(method = POST) |
@PutMapping("/path") |
@RequestMapping(method = PUT) |
@DeleteMapping("/path") |
@RequestMapping(method = DELETE) |
改写上面的例子:
@GetMapping("/get") public String testGet() { return "success"; }
代码更简洁,语义更清晰。
小结
- 使用
@RequestMapping可灵活控制路径、方法和响应格式; - 日常开发中,优先使用
@GetMapping、@PostMapping等快捷注解; - 类上的
@RequestMapping用于统一接口前缀,便于模块化管理。