? Java 后端參數接收注解 & 前端傳參格式對照
后端注解 前端 Content-Type 前端傳參方式 說明 @RequestParam
application/x-www-form-urlencoded
URL參數 / form表單提交 / Postman form-data 常用于 key=value 形式的參數;適合少量簡單參數 @RequestParam
URL拼接 /api/test?id=123&name=abc
Get/Post 請求都行,參數在 query string @PathVariable
不關心 Content-Type URL 路徑參數 @GetMapping("/api/test/{id}")
,URL 要寫 /api/test/123
@RequestBody
application/json
JSON 格式,raw 模式,post body 傳參 專門接收 JSON 格式,適合復雜對象、數組傳遞 @ModelAttribute
application/x-www-form-urlencoded
或 multipart/form-data
key=value 的 form-data,或表單提交 接收 form-data 或表單數據,會自動封裝為對象 @RequestPart
multipart/form-data
文件上傳,配合 JSON、表單混合傳遞 用于上傳文件或文件 + 數據的組合提交(MultipartFile 接收) MultipartFile
multipart/form-data
form-data 方式上傳文件 專門處理文件上傳 HttpServletRequest
/ HttpServletResponse
不關心 Content-Type 一般用于文件下載、復雜定制化請求 原生的請求、響應操作,常見于流下載、session處理
? 詳細解釋
1?? @RequestParam
@GetMapping ( "/test" )
public String test ( @RequestParam String name, @RequestParam Integer age)
前端傳參
GET : /test?name=Tom&age=12
POST : application/x-www-form-urlencoded
name=Tom&age=12
2?? @PathVariable
@GetMapping ( "/test/{id}" )
public String test ( @PathVariable Long id)
前端傳參
3?? @RequestBody
@PostMapping ( "/test" )
public String test ( @RequestBody User user)
前端傳參
{ "name" : "Tom" , "age" : 12
}
常用于前端傳 JSON 對象、數組 🚨 如果你忘記 Content-Type: application/json
,Spring 會報錯!
4?? @ModelAttribute
@PostMapping ( "/test" )
public String test ( @ModelAttribute User user)
前端傳參
application/x-www-form-urlencoded
name=Tom&age=12
或 multipart/form-data
(主要用在有文件上傳時)
5?? @RequestPart
@PostMapping ( "/upload" )
public String upload ( @RequestPart ( "file" ) MultipartFile file, @RequestPart ( "user" ) String userJson)
前端傳參
multipart/form-data
文件 + JSON 同時上傳 (需要自己在前端 form-data
里傳 JSON 字符串,再后端反序列化)
6?? MultipartFile
@PostMapping ( "/upload" )
public String upload ( @RequestParam ( "file" ) MultipartFile file)
前端傳參
multipart/form-data
直接在 form-data
里傳文件。
? 常見前端傳參方式 & 后端適配
前端請求 Content-Type 后端接收注解 URL傳參 /api?id=1&name=Tom
無
或 application/x-www-form-urlencoded
@RequestParam
/ @PathVariable
表單提交 key=value
application/x-www-form-urlencoded
@RequestParam
/ @ModelAttribute
JSON {"id":1,"name":"Tom"}
application/json
@RequestBody
文件上傳 multipart/form-data
MultipartFile
/ @RequestPart
文件 + JSON multipart/form-data
@RequestPart
? 總結下選擇建議!
場景 用法 簡單的參數 @RequestParam
+ application/x-www-form-urlencoded
路徑變量(RESTful) @PathVariable
復雜對象/數組(JSON) @RequestBody
+ application/json
表單傳對象 @ModelAttribute
+ application/x-www-form-urlencoded
文件上傳或混合參數 MultipartFile
/ @RequestPart
+ multipart/form-data
文件下載/流操作 HttpServletResponse