Spring MVC 請求類型注解詳解
1. 核心注解分類
Spring MVC 中的請求處理注解分為以下幾類:
類別 | 注解示例 | 作用范圍 |
---|---|---|
方法級注解 | @RequestMapping , @GetMapping 等 | 方法級別 |
參數級注解 | @RequestParam , @RequestBody | 方法參數 |
模型/會話注解 | @ModelAttribute , @SessionAttributes | 方法或類級別 |
2. 方法級注解詳解
@RequestMapping
功能:定義請求映射規則,支持所有 HTTP 方法。
屬性列表:
屬性 | 說明 | 示例 |
---|---|---|
method | 指定支持的 HTTP 方法(如 RequestMethod.GET )。 | method = RequestMethod.POST |
value | 請求路徑(可省略,與 path 等效)。 | value = "/user" 或 path = "/user" |
params | 條件過濾:請求參數需滿足指定條件(如 param1 , !param2 )。 | params = {"name", "!age"} |
headers | 條件過濾:HTTP 頭需滿足指定條件(如 User-Agent:Chrome )。 | headers = "Content-Type=application/json" |
consumes | 限制請求內容類型(如 MediaType.APPLICATION_JSON_VALUE )。 | consumes = MediaType.APPLICATION_JSON_VALUE |
produces | 限制響應內容類型(如 text/html )。 | produces = "text/html" |
@GetMapping / @PostMapping 等
功能:@RequestMapping
的簡化版,按 HTTP 方法分類:
@GetMapping
:對應method = RequestMethod.GET
@PostMapping
:對應method = RequestMethod.POST
@PutMapping
:對應method = RequestMethod.PUT
@DeleteMapping
:對應method = RequestMethod.DELETE
@PatchMapping
:對應method = RequestMethod.PATCH
3. 參數級注解詳解
@RequestParam
功能:綁定 URL 查詢參數或表單參數到方法參數。
屬性列表:
屬性 | 說明 | 示例 |
---|---|---|
value | 參數名稱(可省略,與 name 等效)。 | value = "id" 或 name = "id" |
required | 是否必須(默認 true )。 | required = false |
defaultValue | 參數缺失時的默認值。 | defaultValue = "0" |
示例:
@GetMapping("/user")
public String getUser(@RequestParam("id") int userId) { ... }
@PathVariable
功能:綁定 URL 路徑中的變量到方法參數。
屬性列表:
屬性 | 說明 | 示例 |
---|---|---|
value | 路徑變量名稱。 | value = "id" |
required | 是否必須(默認 true )。 | required = false |
示例:
@GetMapping("/user/{id}")
public String getUser(@PathVariable("id") String userId) { ... }
@RequestBody
功能:將 HTTP 請求體(如 JSON/XML)反序列化為 Java 對象。
屬性:
- 無顯式屬性,直接用于方法參數。
- 依賴
MappingJackson2HttpMessageConverter
(JSON)或自定義轉換器。
示例:
@PostMapping("/user")
public User createUser(@RequestBody User user) { ... }
@RequestHeader
功能:綁定 HTTP 請求頭到方法參數。
屬性列表:
屬性 | 說明 | 示例 |
---|---|---|
value | 請求頭名稱。 | value = "User-Agent" |
required | 是否必須(默認 true )。 | required = false |
defaultValue | 缺省值。 | defaultValue = "unknown" |
示例:
@GetMapping("/headers")
public String getHeaders(@RequestHeader("User-Agent") String userAgent) { ... }
@CookieValue
功能:綁定 Cookie 值到方法參數。
屬性列表:
屬性 | 說明 | 示例 |
---|---|---|
value | Cookie 名稱。 | value = "JSESSIONID" |
required | 是否必須(默認 true )。 | required = false |
defaultValue | 缺省值。 | defaultValue = "not-set" |
示例:
@GetMapping("/cookie")
public String getCookie(@CookieValue("theme") String theme) { ... }
4. 模型/會話注解
@ModelAttribute
功能:
- 方法級:在目標方法執行前預處理模型數據(如填充對象)。
- 參數級:將請求參數綁定到 Java 對象。
示例:
// 方法級:預加載數據
@ModelAttribute("user")
public User getUser() {return new User();
}// 參數級:綁定參數到對象
@PostMapping("/user")
public String saveUser(@ModelAttribute User user) { ... }
@SessionAttributes
功能:將模型屬性存儲到 HTTP Session。
屬性:
value
:需存儲的屬性名列表(如{"user"}
)。types
:需存儲的屬性類型列表。
示例:
@Controller
@SessionAttributes({"user"})
public class UserController { ... }
5. 文件上傳注解
@RequestPart
功能:處理多部分請求中的文件或參數(結合 @RequestParam
)。
示例:
@PostMapping("/upload")
public String uploadFile(@RequestPart("file") MultipartFile file) { ... }
6. 總結表格
注解類型 | 注解名稱 | 作用 | 參數示例 |
---|---|---|---|
方法級 | @RequestMapping | 定義請求映射規則(路徑、方法、條件等)。 | method = POST, consumes = "application/json" |
HTTP 方法專用 | @GetMapping | 僅處理 GET 請求。 | /user/{id} |
參數綁定 | @RequestParam | 綁定查詢參數或表單參數。 | @RequestParam("id") int userId |
路徑變量 | @PathVariable | 綁定 URL 路徑中的變量。 | @PathVariable("id") String userId |
請求體 | @RequestBody | 反序列化請求體為對象。 | @RequestBody User user |
HTTP 頭 | @RequestHeader | 綁定請求頭值。 | @RequestHeader("User-Agent") String agent |
Cookie | @CookieValue | 綁定 Cookie 值。 | @CookieValue("theme") String theme |
模型/會話 | @ModelAttribute | 綁定對象或預加載模型數據。 | @ModelAttribute User user |
文件上傳 | @RequestPart | 處理多部分請求中的文件或參數。 | @RequestPart("file") MultipartFile file |
關鍵總結
- 方法級注解:定義請求路徑和條件,優先使用
@GetMapping
等 HTTP 方法專用注解。 - 參數級注解:根據數據來源(路徑、請求體、請求頭等)選擇對應注解。
- 模型/會話:
@ModelAttribute
用于對象綁定和預處理,@SessionAttributes
管理會話數據。 - 最佳實踐:
- 使用
@RequestBody
處理 JSON/XML 請求體。 - 通過
@RequestParam
或@PathVariable
精確控制參數來源。 - 結合
@Valid
注解實現參數校驗(需@ControllerAdvice
處理異常)。
- 使用