SpringBoot接收參數(shù)所有方式總結(jié)
方法形參接收參數(shù)【不推薦】
- 此場(chǎng)景適用于請(qǐng)求參數(shù)比較少的情況
- Springboot3.2會(huì)異常報(bào)錯(cuò):
Name for argument of type [java.lang.String] not specified, and parameter name information not available via reflection. Ensure that the compiler uses the '-parameters' flag.
- 解決方案
@RequestMapping("/test1") public String test1(String name,String age) { return String.format("name:%s,age:%s", name, age); }
以實(shí)體類(lèi)接受參數(shù) 【不推薦】
- 此場(chǎng)景適用于請(qǐng)求參數(shù)比較多的情況
@Getter @Setter public static class DTO { private String name; ? private Integer age; } ? @RequestMapping("/test2") public String test2(DTO request) { return String.format("name:%s,age:%s", request.getName(), request.getAge()); }
以形參和實(shí)體類(lèi)接受參數(shù) 【不推薦】
- Springboot3.2會(huì)異常報(bào)錯(cuò):
Name for argument of type [java.lang.String] not specified, and parameter name information not available via reflection. Ensure that the compiler uses the '-parameters' flag.
- 解決方案
@RequestMapping("/test3") public String test3(DTO requestDto,String sex) { return String.format("name:%s,age:%s,sex:%s", requestDto.getName(), requestDto.getAge(),sex); }
上述三種接受參數(shù)的方式,只能用來(lái)獲取query-params,form-data,x-www-form-urlencoded格式數(shù)據(jù)
@PathVariable注解
@PathVariable
注解可用于處理請(qǐng)求 URI 映射中的模板變量,并將其綁定到 Controller 方法參數(shù)
- 使用
@PathVariable
注解來(lái)提取 URI 的模板部分,該部分由變量{name}
表示
@RequestMapping("/test4/{name}/{age}") public String test4(@PathVariable("name") String name,@PathVariable("age") Integer age) { return String.format("name:%s,age:%s", name, age); }
指定路徑變量名
由于方法參數(shù)和路徑變量的名稱(chēng)相同,可以不用主動(dòng)設(shè)置模板路徑變量的名稱(chēng)。如果路徑變量名不同,可以在
@PathVariable
注解的參數(shù)中指定
@GetMapping("/test5/{name}") public String test4(@PathVariable("name") String id) { return String.format("name:%s",id); }
- 單個(gè)請(qǐng)求中的多個(gè)路徑變量
@GetMapping("/test5/{name}/{id}") public String test5(@PathVariable(value = "name") String name,@PathVariable(value = "id") String id) { return String.format("name:%s id:%s", name, id); }
java.util.Map<String, String>
類(lèi)型的方法參數(shù)來(lái)處理多個(gè) `@PathVariable 參數(shù) [不推薦]
@GetMapping("/test5/{name}/{id}") public String test6(@PathVariable Map<String,String> request) { return JSON.toJSONString(request); }
- 可選擇的路徑變量
@RequestMapping(value = {"/test6","test6/{name}/{age}"}) public String test6(@PathVariable("name") String name,@PathVariable("age") Integer age) { return String.format("name:%s,age:%s", name, age); }
咋一看,上述 Controller 應(yīng)該可以處理 /test6
和 /test6/smile/32
請(qǐng)求。但是,由于 @PathVariables
所注解的方法參數(shù)默認(rèn)為必選參數(shù),因此它無(wú)法處理 /api/employeeswithrequired
請(qǐng)求
有三種不同的方法來(lái)處理這個(gè)問(wèn)題
設(shè)置required為false
@RequestMapping(value = {"/test6","test6/{name}/{age}"}) public String test6(@PathVariable(value = "name",required = false) String name,@PathVariable(value = "age",required = false) Integer age) { return String.format("name:%s,age:%s", name, age); }
使用 java.util.Optional
@RequestMapping(value = {"/test7","test7/{name}/{age}"}) public String test7(@PathVariable Optional<String> name,@PathVariable Optional<String> age) { return String.format("name:%s,age:%s", name.orElse("null"), age.orElse("null")); }
使用 Map<String, String> 類(lèi)型的方法參數(shù) [不推薦]
@RequestMapping(value = {"/test8","test8/{name}/{age}"}) public String test8(@PathVariable Map<String,String> request) { return String.format("name:%s,age:%s", request.get("name"), request.get("age")); }
@RequestParam
可以使用 @RequestParam
從請(qǐng)求中提取查詢(xún)參數(shù)、表單參數(shù)甚至是多個(gè)參數(shù)
指定請(qǐng)求參數(shù)名稱(chēng)
如果變量名稱(chēng)和參數(shù)名稱(chēng)不同,可以使用
name
屬性配置@RequestParam
名稱(chēng):
@RequestMapping("/test9") public String test9(@RequestParam("name") String name,@RequestParam("age") Integer age) { return String.format("name:%s,age:%s", name, age); ? }
也可以使用 @RequestParam(value = "name")
或直接使用 @RequestParam("name")
可選的請(qǐng)求參數(shù)
使用
@RequestParam
注解的方法參數(shù)默認(rèn)為必填參數(shù)。這意味著,如果請(qǐng)求中沒(méi)有該參數(shù),就會(huì)返回 400 錯(cuò)誤- 可以使用
required
屬性將@RequestParam
配置為可選參數(shù):
- 可以使用
@RequestMapping("/test10") public String test10(@RequestParam(value = "name",required = false) String name,@RequestParam(value = "age",required = false) Integer age) { return String.format("name:%s,age:%s", name, age); }
如果沒(méi)有指定參數(shù),方法參數(shù)將綁定為 null
使用 Java 8 Optional
@RequestMapping("/test11") public String test11(@RequestParam(value = "name") Optional<String> name,@RequestParam(value = "age") Optional<Integer> age) { return String.format("name:%s,age:%s", name.orElse(null), age.orElse(null)); }
在這種情況下,不需要指定
required
屬性。如果沒(méi)有提供請(qǐng)求參數(shù),則使用默認(rèn)值:
請(qǐng)求參數(shù)的默認(rèn)值
還可以使用 defaultValue
屬性為 @RequestParam
設(shè)置默認(rèn)值
@RequestMapping("/test12") public String test12(@RequestParam(value = "name",defaultValue = "smile") Optional<String> name,@RequestParam(value = "age") Optional<Integer> age) { return String.format("name:%s,age:%s", name.orElse(null), age.orElse(null)); }
與 required=false
類(lèi)似,用戶(hù)不再需要提供參數(shù):
注意,當(dāng)設(shè)置 defaultValue
屬性時(shí),required
會(huì)被被設(shè)置為 false
映射所有參數(shù)
還可以使用 Map
來(lái)封裝多個(gè)參數(shù),而無(wú)需定義它們的名稱(chēng)(name
)或數(shù)量:
@RequestMapping("/test13") public String test13(@RequestParam Map<String,String> request) { return String.format("name:%s,age:%s", request.get("name"), request.get("age")); }
多值參數(shù)(列表/數(shù)組)
一個(gè) @RequestParam
可以有多個(gè)值:
@RequestMapping("/test14") public String test14(@RequestParam("id") List<String> idList) { return String.format(JSON.toJSONString(idList)); }
@RequestBody
將HttpRequest主體映射到方法上實(shí)體屬性中
以字符串的方式接收 body 的數(shù)據(jù)
@PostMapping("/test15") public String test15(@RequestBody String requestString) { return requestString; }
以Map的方式接收body 的數(shù)據(jù)
@RequestMapping("/test16") public String test16(@RequestBody Map<String,Object> requestMap) { return String.format(JSON.toJSONString(requestMap)); }
以實(shí)體類(lèi)的方式接收body 的數(shù)據(jù) 【最常用】
@RequestMapping("/test17") public String test17(@RequestBody DTO requestDto) { return String.format(JSON.toJSONString(requestDto)); }
當(dāng)body中沒(méi)有任何數(shù)據(jù)傳遞時(shí),會(huì)拋出異常:Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public java.lang.String com.fs.smile.home.controller.RequestController.test16(java.util.Map<java.lang.String, java.lang.Object>)]
這種情況,應(yīng)該如何解決
可以使用 required
屬性將 @RequestBody
配置為可選參數(shù)
@RequestMapping("/test17") public String test17(@RequestBody DTO requestDto) { return String.format(JSON.toJSONString(requestDto)); }
使用 Java 8 Optional
在這種情況下,不需要指定 required
屬性
@RequestMapping("/test18") public String test18(@RequestBody Optional<Map<String,Object> > requestMap) { return String.format(JSON.toJSONString(requestMap.orElse(null))); }
@RequestBody接收數(shù)據(jù)的格式要求
- Content-Type: application/json
- Content-Type: application/xml
- Content-Type: text/plain
- Content-Type: application/octet-stream
根據(jù)不同的Content-Type等情況,Spring-MVC會(huì)采取不同的HttpMessageConverter實(shí)現(xiàn)來(lái)進(jìn)行信息轉(zhuǎn)換解析。@RequestBody不能用來(lái)處理application/x-www-form-urlencoded
或 multipart/form-data
格式的請(qǐng)求數(shù)據(jù),如果嘗試使用 @RequestBody
來(lái)處理這類(lèi)請(qǐng)求,通常會(huì)遇到 415 Unsupported Media Type 異常。要處理這兩種格式的數(shù)據(jù),應(yīng)該使用 @RequestParam
或 @ModelAttribute
注解
@RequestHeader
RequestHeader主要用來(lái)獲取請(qǐng)求當(dāng)中的請(qǐng)求頭
- 獲取單個(gè)header屬性
@RequestMapping("/test20") public String test20(@RequestHeader("name") String name,@RequestHeader("age") Integer age) { return String.format("name:%s,age:%s", name, age); }
當(dāng)header中不存在該參數(shù)時(shí),系統(tǒng)會(huì)拋出400的異常,可以參考@PathVariable的處理方案
獲取所有header屬性
@RequestMapping("/test21") public String test21(@RequestHeader Map<String,String> headers) { return String.format("name:%s,age:%s", headers.get("name"), headers.get("age")); }
獲取header對(duì)象
@RequestMapping("/test22") public String test22(@RequestHeader HttpHeaders headers) { return String.format("name:%s,age:%s", headers.get("name"), headers.get("age")); }
以上就是SpringBoot接受參數(shù)所有方式總結(jié)的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot接受參數(shù)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
ElasticSearch查詢(xún)文檔基本操作實(shí)例
這篇文章主要為大家介紹了ElasticSearch查詢(xún)文檔基本操作實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02Spring MVC 學(xué)習(xí) 之 - URL參數(shù)傳遞詳解
本篇文章主要介紹了SpringMVC-URL參數(shù)傳遞,在學(xué)習(xí) Spring Mvc 過(guò)程中,有必要來(lái)先了解幾個(gè)關(guān)鍵參數(shù),有興趣的可以了解一下。2017-01-01Java通過(guò)在主循環(huán)中判斷Boolean來(lái)停止線(xiàn)程的方法示例
這篇文章主要介紹了Java通過(guò)在主循環(huán)中判斷Boolean來(lái)停止線(xiàn)程的方法,結(jié)合具體實(shí)例形式分析了java針對(duì)線(xiàn)程的判斷與停止操作相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-04-04解決idea 項(xiàng)目編譯后沒(méi)有class文件的問(wèn)題
這篇文章主要介紹了解決idea 項(xiàng)目編譯后沒(méi)有class文件的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-12-12SpringBoot實(shí)現(xiàn)RabbitMQ監(jiān)聽(tīng)消息的四種方式
本文主要介紹了SpringBoot實(shí)現(xiàn)RabbitMQ監(jiān)聽(tīng)消息的四種方式,包括@RabbitListener,MessageListener接口,MessageListenerAdapter適配器,@RabbitHandler這幾種,感興趣的可以了解一下2024-05-05spring-boot項(xiàng)目啟動(dòng)遲緩異常排查解決記錄
這篇文章主要為大家介紹了spring-boot項(xiàng)目啟動(dòng)遲緩異常排查解決記錄,突然在本地啟動(dòng)不起來(lái)了,表象特征就是在本地IDEA上運(yùn)行時(shí),進(jìn)程卡住也不退出,應(yīng)用啟動(dòng)時(shí)加載相關(guān)組件的日志也不輸出2022-02-02