首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Spring @RequestMapping 註解完全解析:URL 映射、請求方法限定、路徑變量與最佳實踐

     編輯:Java 綜合教學

核心屬性

屬性類型說明示例
value / pathString[]映射 URL 路徑,支援多值 (同一方法處理多路徑)@RequestMapping({"/user", "/member"})
methodRequestMethod[]限定 HTTP 方法 (GET/POST/PUT/DELETE/PATCH 等)@RequestMapping(method = RequestMethod.GET)
paramsString[]請求參數條件 (存在/不存在/等於/不等於)@RequestMapping(params = "id")
headersString[]請求頭條件@RequestMapping(headers = "content-type=application/json")
consumesString[]請求體 Content-Type (如 application/json)@RequestMapping(consumes = "application/json")
producesString[]響應 Content-Type (如 application/json;charset=UTF-8)@RequestMapping(produces = "application/json")

三大使用模式

1. 類級別定義公共前綴

@RestController
@RequestMapping("/api/v1/users")
public class UserController {
    // 所有方法自動帶有 /api/v1/users 前綴
}

2. 方法級別精確映射

@GetMapping("/{id}")           // 組合註解:@RequestMapping(method=GET, value="/{id}")
public User getUser(@PathVariable Long id) { ... }

@PostMapping
public User createUser(@RequestBody User user) { ... }

@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user) { ... }

@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) { ... }

3. 窄化映射:參數/頭/媒體類型條件

// 僅處理帶有 version=2 參數的 GET 請求
@GetMapping(value = "/profile", params = "version=2")
public User profileV2() { ... }

// 僅處理 JSON 請求體
@PostMapping(consumes = "application/json")
public void handleJson(@RequestBody Dto dto) { ... }

// 明確響應 JSON
@GetMapping(produces = "application/json;charset=UTF-8")
public User get() { ... }

路徑變量與正則約束

// 基礎路徑變量
@GetMapping("/{id}")
public User get(@PathVariable Long id) { ... }

// 正則約束:id 必須為數字
@GetMapping("/{id:\\d+}")
public User getByNumber(@PathVariable Long id) { ... }

// 多路徑變量
@GetMapping("/users/{userId}/orders/{orderId}")
public Order getOrder(@PathVariable Long userId, @PathVariable Long orderId) { ... }

Spring 4.3+ 組合註解 (推薦)

組合註解等價 @RequestMapping
@GetMappingmethod = RequestMethod.GET
@PostMappingmethod = RequestMethod.POST
@PutMappingmethod = RequestMethod.PUT
@DeleteMappingmethod = RequestMethod.DELETE
@PatchMappingmethod = RequestMethod.PATCH

優點:語義更清晰、減少屬性寫錯、IDE 提示更友好。

常見坑點

  • 類級 @RequestMapping 缺少前導 / → 路徑拼接錯誤 (如 api/users + /list = api/users/list 而非 /api/users/list)。
  • 同一路徑不同 HTTP 方法未分開 → 405 Method Not Allowed。
  • @PathVariable 變量名與路徑佔位符不一致 → 需指定 @PathVariable("id") Long userId。
  • 消費 application/json 但請求無 Content-Type 或類型不匹配 → 415 Unsupported Media Type。

總結

@RequestMapping 是 Spring MVC 請求分發的核心註解。掌握「類級前綴 + 方法級精確映射 + 條件窄化 + 組合註解」四層用法,並避開常見路徑拼接、媒體類型不匹配陷阱,能編寫清晰、健壯、符合 REST 風格的控制層代碼。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved