@RequestParam @RequestBody @PathVariable用法詳解
三個注解都是在我們進行請求時對服務端參數(shù)進行封裝的,那么具體三個注解的使用,什么情況下,什么條件下使用呢?
一、@RequestParam
- @RequestParam接收的參數(shù)是來自于RequestHeader中,即請求頭。
@RequestParam用來處理 Content-Type 為 application/x-www-form-urlencoded 編碼的內(nèi)容,Content-Type默認為該屬性。且常用于Get請求其他請求也可使用;
用處:(僅根據(jù)自己學習總結(jié)得出,若有不對請指出)在傳遞參數(shù)的情況下,不管參數(shù)是否必須傳值的情況下皆可使用
例如:
http://localhost:8080/test/?name=”xxx”
@GetMapping("/test")
String test(@RequestParam("name") String name);
- 值得注意的是不支持批量插入數(shù)據(jù)啊,如果改用 json 字符串來傳值的話,類型設置為 application/json,點擊發(fā)送的話,會報錯,后臺接收不到值,為 null。
二、@RequestBody
@RequestBody主要用來接收前端傳遞給后端的json字符串中的數(shù)據(jù)的(請求體中的數(shù)據(jù)的);
比如:application/json、application/xml等類型的數(shù)據(jù)
且只能用于Post請求,Get方式?jīng)]有請求體接收不到參數(shù)
@PostMapping("/test2")
String test2(@RequestBody Product product);
三、@PathVariable
@PathVariable是spring3.0的一個新功能:接收請求路徑中占位符的值
一般也是用于Get請求,URL 中的 {xxx} 占位符可以通過@PathVariable(“xxx“) 綁定到操作方法的入?yún)⒅?br> 例如:
localhost:8080/id/1文章來源:http://www.zghlxwxcb.cn/news/detail-641582.html
@GetMapping("id/{id}")
public ObjectfindById(@PathVariable("id") long id) {
return studentService.findById(id);
}
四、@RequestParam與@RequestBody對比
兩種注解使用多使用在偽Http客戶端請求時對參數(shù)進行指定識別時使用,如OpenFeign在微服務之間參數(shù)調(diào)用時。
@RequestParam一般用來接收一個參數(shù),比如單獨的id或者name等參數(shù),@RequestBody大多數(shù)用來對某個封裝對象進行接收,從前端傳來的數(shù)據(jù)封裝成對象進行接收。
@RequestParam也是可以對數(shù)組對象進行封裝的例如:文章來源地址http://www.zghlxwxcb.cn/news/detail-641582.html
@GetMapping("/test3")
public String test3(@RequestParam("ids") String[] ids){
for (String id : ids) {
log.info("id:{}",id);
}
return "test3 ok端口"+port;
}
到了這里,關于@RequestParam @RequestBody @PathVariable用法詳解的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!