@RequestBody 和 @RequestParam可以同时使用
@RequestParam和@RequestBody這兩個注解是可以同時使用的。
網上有很多博客說@RequestParam 和@RequestBody不能同時使用,這是錯誤的。根據HTTP協議,并沒有說post請求不能帶URL參數,經驗證往一個帶有參數的URL發送post請求也是可以成功的。只不過,我們日常開發使用GET請求搭配@RequestParam,使用POST請求搭配@RequestBody就滿足了需求,基本不怎么同時使用二者而已。
? 自己個人實際驗證結果:
package com.example.model;import java.util.List;public class PramInfo {public int getId() {return id;}public void setId(int id) {this.id = id;}public String getStr() {return str;}public void setStr(String str) {this.str = str;}private int id;private String str;}package com.example.demo;import com.example.model.PramInfo; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController;@RestController @RequestMapping(value = "/test") public class TestContoller {@RequestMapping(value = "/dxc")public String print(PramInfo info) {return info.getId() + ": :" + info.getStr();}@RequestMapping(value = "/getUserJson")public String getUserJson(@RequestParam(value = "id") int id, @RequestParam(value = "name2", required = false) String name2, @RequestBody PramInfo pramInfo) {return (id + "--" + name2 + ";paramInfo:" + pramInfo.getStr() + ";pramInfo.id:" + pramInfo.getId());} }在postman發送如下post請求,返回正常:
body中參數如下:
? 從結果來看,post請求URL帶參數是沒有問題的,所以@RequestParam和@RequestBody是可以同時使用的【經測試,分別使用Postman 和 httpClient框架編程發送http請求,后端@RequestParam和@RequestBody都可以正常接收請求參數,所以個人認為可能一些前端框架不支持或者沒必要這么做,但是不能說@RequestParam和@RequestBody 不能同時使用】。
值得注意的地方:
1、postman的GET請求是不支持請求body的;
2、
@GetMapping(value = "/dxc")public String print(PramInfo info) {return info.getId() + ": :" + info.getStr();}這種請求方式,不加@RequestParam注解,也能直接取出URL后面的參數,即參數可以與定義的類互相自動轉化。
3、
@PostMapping(value = "/getUserJson")public String getUserJson(@RequestParam(value = "id") int id, @RequestParam(value = "name2", required = false) String name2, @RequestBody PramInfo pramInfo) {return (id + "--" + name2 + ";paramInfo:" + pramInfo.getStr() + ";pramInfo.id:" + pramInfo.getId());如果請求中的body沒有ParamInfo對象對應的json串,即當body為空(連json串的{}都沒有)時,會報請求body空異常:
2018-05-12 23:45:27.494 WARN 6768 --- [nio-8080-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public java.lang.Stringcom.example.demo.TestContoller.getUserJson(int,java.lang.String,com.example.model.PramInfo) -05-12 23:45:27.494 WARN 6768 --- [nio-8080-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public java.lang.String com.example.demo.TestContoller.getUserJson(int,java.lang.String,com.example.model.PramInfo) 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的@RequestBody 和 @RequestParam可以同时使用的全部內容,希望文章能夠幫你解決所遇到的問題。