概述
@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) {// 刪除訂單}
}