| 屬性 | 類型 | 說明 | 示例 |
|---|---|---|---|
| value / path | String[] | 映射 URL 路徑,支援多值 (同一方法處理多路徑) | @RequestMapping({"/user", "/member"}) |
| method | RequestMethod[] | 限定 HTTP 方法 (GET/POST/PUT/DELETE/PATCH 等) | @RequestMapping(method = RequestMethod.GET) |
| params | String[] | 請求參數條件 (存在/不存在/等於/不等於) | @RequestMapping(params = "id") |
| headers | String[] | 請求頭條件 | @RequestMapping(headers = "content-type=application/json") |
| consumes | String[] | 請求體 Content-Type (如 application/json) | @RequestMapping(consumes = "application/json") |
| produces | String[] | 響應 Content-Type (如 application/json;charset=UTF-8) | @RequestMapping(produces = "application/json") |
@RestController
@RequestMapping("/api/v1/users")
public class UserController {
// 所有方法自動帶有 /api/v1/users 前綴
}
@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) { ... }
// 僅處理帶有 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) { ... }
| 組合註解 | 等價 @RequestMapping |
|---|---|
| @GetMapping | method = RequestMethod.GET |
| @PostMapping | method = RequestMethod.POST |
| @PutMapping | method = RequestMethod.PUT |
| @DeleteMapping | method = RequestMethod.DELETE |
| @PatchMapping | method = RequestMethod.PATCH |
優點:語義更清晰、減少屬性寫錯、IDE 提示更友好。
@RequestMapping 缺少前導 / → 路徑拼接錯誤 (如 api/users + /list = api/users/list 而非 /api/users/list)。@PathVariable 變量名與路徑佔位符不一致 → 需指定 @PathVariable("id") Long userId。application/json 但請求無 Content-Type 或類型不匹配 → 415 Unsupported Media Type。@RequestMapping 是 Spring MVC 請求分發的核心註解。掌握「類級前綴 + 方法級精確映射 + 條件窄化 + 組合註解」四層用法,並避開常見路徑拼接、媒體類型不匹配陷阱,能編寫清晰、健壯、符合 REST 風格的控制層代碼。