@RequestMapping
是 Spring Framework 中一個核心注解,用于在 Spring MVC(或 Spring WebFlux)中將 HTTP 請求映射到特定的處理器(Controller 中的方法)或處理器類。它告訴 Spring 框架:當一個匹配特定條件的 HTTP 請求到達時,應該調用哪個方法來處理該請求。
簡單來說,它是定義 Web 請求端點(API 接口)的基礎。
以下是 @RequestMapping
的關鍵功能和用法:
-
映射位置:
- 類級別: 標注在 Controller 類上,為該類中所有處理器方法提供一個公共的 URL 路徑前綴。
- 方法級別: 標注在 Controller 類內部的方法上,定義該方法的具體映射路徑(相對于類級別的路徑)和處理邏輯。通常一個方法處理一個具體的請求。
-
映射內容(屬性):
@RequestMapping
接受多個屬性來精確指定它要匹配的請求特征:value
或path
(最常用): 指定請求的 URL 路徑模式。支持 Ant 風格通配符 (*
,**
,?
) 和路徑變量 ({variable}
)。@RequestMapping("/users") // 類級別前綴 @RestController public class UserController {@RequestMapping("/profile") // 實際映射到 /users/profilepublic String userProfile() { ... }@RequestMapping("/orders/{orderId}") // 路徑變量public String getOrder(@PathVariable String orderId) { ... } }
method
: 指定請求的 HTTP 方法 (GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS 等)。這是定義 RESTful 風格 API 的關鍵。@RequestMapping(value = "/users", method = RequestMethod.POST) // 只處理 POST /users public User createUser(@RequestBody User user) { ... }@RequestMapping(value = "/users/{id}", method = RequestMethod.GET) // 只處理 GET /users/{id} public User getUser(@PathVariable Long id) { ... }
params
: 要求請求必須包含特定的請求參數,或者參數具有特定值。支持表達式 (=
,!=
,!
存在)。@RequestMapping(value = "/search", params = "q") // 必須有 q 參數 public List<User> searchUsers(@RequestParam String q) { ... }@RequestMapping(value = "/activate", params = "token=valid") // 必須有 token 參數且值為 'valid' public void activateAccount() { ... }
headers
: 要求請求必須包含特定的 HTTP 頭信息,或者頭信息具有特定值。@RequestMapping(value = "/data", headers = "X-Custom-Header=MyValue") // 需要特定自定義頭 public String getData() { ... }@RequestMapping(value = "/pdf", headers = "Accept=application/pdf") // 要求 Accept 頭包含 pdf public ResponseEntity<byte[]> getPdf() { ... }
consumes
: 指定處理器方法能夠接收(消費)的請求內容類型 (Content-Type)。例如application/json
,application/xml
。@RequestMapping(value = "/users", method = RequestMethod.POST, consumes = "application/json") public User createUserJson(@RequestBody User user) { ... } // 只處理 Content-Type 為 JSON 的 POST
produces
: 指定處理器方法返回的響應內容類型 (Content-Type)。客戶端可以通過Accept
頭來匹配。@RequestMapping(value = "/users/{id}", method = RequestMethod.GET, produces = "application/json") public User getUserJson(@PathVariable Long id) { ... } // 返回 JSON@RequestMapping(value = "/users/{id}", method = RequestMethod.GET, produces = "application/xml") public User getUserXml(@PathVariable Long id) { ... } // 返回 XML (同一個路徑不同返回類型)
-
組合注解 (更簡潔的替代):
為了簡化常見 HTTP 方法的映射,Spring 提供了基于@RequestMapping
的組合注解(元注解)。它們內部已經設置了method
屬性,語法更簡潔:@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)
現代 Spring Boot 應用中,推薦優先使用這些組合注解,代碼更清晰。
-
工作原理:
當一個 HTTP 請求到達 DispatcherServlet(Spring MVC 前端控制器)時:- DispatcherServlet 會查詢一個或多個
HandlerMapping
組件。 HandlerMapping
組件(如RequestMappingHandlerMapping
)負責檢查所有帶有@Controller
或@RestController
注解的類及其方法上的@RequestMapping
(或組合注解)定義。- 它會根據請求的 URL 路徑、HTTP 方法、請求頭、參數、內容類型等,找到最匹配的處理器方法(
HandlerMethod
)。 - 找到匹配的方法后,DispatcherServlet 就會調用該方法來處理請求并生成響應。
- DispatcherServlet 會查詢一個或多個
總結:
@RequestMapping
是 Spring MVC 中定義請求處理入口的核心注解。- 它通過
path/value
,method
,params
,headers
,consumes
,produces
等屬性精確匹配傳入的 HTTP 請求。 - 可以放在類上(定義公共前綴)和方法上(定義具體端點)。
- 組合注解 (
@GetMapping
,@PostMapping
等) 是更簡潔、更現代的寫法,推薦優先使用。 - 它是構建 RESTful API 和傳統 Web 控制器的基礎。
理解 @RequestMapping
是掌握 Spring Web 開發的關鍵第一步。