@RequestMapping 是 Spring MVC 中 定义请求映射规则的核心注解,用于将 HTTP 请求映射到 具体Controller 以及controller中的具体方法。
|------------------|---------------------------|-----------------------------------------------|
| 参数 | 作用描述 | 示例 |
| value / path | 指定映射的URL路径(可多路径) | @RequestMapping("/api/user") |
| method | 限制HTTP请求方法(GET、POST等) | method = RequestMethod.PUT |
| params | 要求请求必须包含特定参数 | params = "type=admin" (参数须为 type=admin) |
| headers | 限制请求头条件 | headers = "Content-Type=application/json" |
| consumes | 指定处理的请求内容类型(Content-Type) | consumes = MediaType.APPLICATION_JSON_VALUE |
| produces | 指定响应内容的类型(Accept头匹配) | produces = "text/plain;charset=UTF-8" |
快捷组合注解
Spring 4.3+ 提供简化的HTTP方法注解,替代 method 参数配置:
@GetMapping → @RequestMapping(method = GET)
@PostMapping → @RequestMapping(method = POST)
@PutMapping、@DeleteMapping、@PatchMapping
@Controller
@RequestMapping("/springmvc")
@ResponseBody
public class HelloController {
@RequestMapping(value = "/hello",method = RequestMethod.GET)
public String hello(){
System.out.println("HelloController.hello");
return "hello springmvc";
}
@GetMapping("/hello2")
public String hello2(){
System.out.println("HelloController.hello");
return "hello springmvc";
}
}