SpringMVC核心注解:@RequestMapping详解
概述
@RequestMapping是SpringMVC中最核心的注解之一,用于将HTTP请求映射到MVC和REST控制器的处理方法上。
基本功能
@RequestMapping主要用于:
- 映射URL到控制器类或方法
- 定义请求方法类型(GET、POST等)
- 定义请求参数、请求头等条件
使用位置
类级别:定义基本请求路径
@RequestMapping("/order")
@Controller
public class OrderController {// ...
}
方法级别:定义具体路径和请求方法
@RequestMapping(value = "/findAll", method = RequestMethod.GET)
@ResponseBody
public List<Order> findAll() {// ...
}
主要属性
属性名 | 说明 | 示例 |
---|---|---|
value/path | 映射的URL路径 | @RequestMapping("/orders") |
method | 请求方法类型 | method = RequestMethod.GET |
params | 请求方法参数 | params = "type=book" |
headers | 请求头条件 | headers = "content-type=text/*" |
consumes | 请求内容类型 | consumes = “application/json” |
produces | 响应内容类型 | produces = “application/json” |
常见组合注解
Spring 4.3+ 提供了更简洁的派生注解代码
注解 | 等价于 |
---|---|
@GetMapping | @RequestMapping(method = RequestMethod.GET) |
@PostMapping | @RequestMapping(method = RequestMethod.POST) |
@PutMapping | @RequestMapping(method = RequestMethod.PUT) |
@DeleteMapping | @RequestMapping(method = RequestMethod.DELETE) |
@PatchMapping | @RequestMapping(method = RequestMethod.PATCH) |
路径变量
可以与@PathVariable配合使用
@GetMapping("/orders/{id}")
public Order getOrder(@PathVariable Long id) {// ...
}
示例代码
@RestController
@RequestMapping("/api/orders")
public class OrderController {@GetMappingpublic List<Order> getAll() {// 获取所有订单}@GetMapping("/{id}")public Order getById(@PathVariable Long id) {// 获取特定ID的订单}@PostMapping@ResponseStatus(HttpStatus.CREATED)public Order create(@RequestBody Order order) {// 创建新订单}@PutMapping("/{id}")public Order update(@PathVariable Long id, @RequestBody Order order) {// 更新订单}@DeleteMapping("/{id}")public void delete(@PathVariable Long id) {// 删除订单}
}