@RequestBody 和 @RequestParam可以同时使用

2022-10-29 10:36:50

@RequestParam和@RequestBody这两个注解是可以同时使用的。

网上有很多博客说@RequestParam 和@RequestBody不能同时使用,这是错误的。根据HTTP协议,并没有说post请求不能带URL参数,经验证往一个带有参数的URL发送post请求也是可以成功的。只不过,我们日常开发使用GET请求搭配@RequestParam,使用POST请求搭配@RequestBody就满足了需求,基本不怎么同时使用二者而已。

自己个人实际验证结果:

packagecom.example.model;importjava.util.List;publicclassPramInfo{publicintgetId(){return id;}publicvoidsetId(int id){this.id= id;}publicStringgetStr(){return str;}publicvoidsetStr(String str){this.str= str;}privateint id;privateString str;}packagecom.example.demo;importcom.example.model.PramInfo;importorg.springframework.web.bind.annotation.RequestBody;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.bind.annotation.RestController;@RestController@RequestMapping(value="/test")publicclassTestContoller{@RequestMapping(value="/dxc")publicStringprint(PramInfo info){return info.getId()+": :"+ info.getStr();}@RequestMapping(value="/getUserJson")publicStringgetUserJson(@RequestParam(value="id")int id,@RequestParam(value="name2", required=false)String name2,@RequestBodyPramInfo pramInfo){return(id+"--"+ name2+";paramInfo:"+ pramInfo.getStr()+";pramInfo.id:"+ pramInfo.getId());}}

在postman发送如下post请求,返回正常:

img

body中参数如下:

img

从结果来看,post请求URL带参数是没有问题的,所以@RequestParam和@RequestBody是可以同时使用的【经测试,分别使用Postman 和 httpClient框架编程发送http请求,后端@RequestParam和@RequestBody都可以正常接收请求参数,所以个人认为可能一些前端框架不支持或者没必要这么做,但是不能说@RequestParam和@RequestBody 不能同时使用】。

值得注意的地方:

1、postman的GET请求是不支持请求body的;

2、

@GetMapping(value="/dxc")publicStringprint(PramInfo info){return info.getId()+": :"+ info.getStr();}

这种请求方式,不加@RequestParam注解,也能直接取出URL后面的参数,即参数可以与定义的类互相自动转化。

3、

@PostMapping(value="/getUserJson")publicStringgetUserJson(@RequestParam(value="id")int id,@RequestParam(value="name2", required=false)String name2,@RequestBodyPramInfo pramInfo){return(id+"--"+ name2+";paramInfo:"+ pramInfo.getStr()+";pramInfo.id:"+ pramInfo.getId());

如果请求中的body没有ParamInfo对象对应的json串,即当body为空(连json串的{}都没有)时,会报请求body空异常:

img

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.String
 com.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)
  • 作者:Archie_java
  • 原文链接:https://lebron.blog.csdn.net/article/details/121312638
    更新时间:2022-10-29 10:36:50