@RequestBody 和 @RequestParam可以同时使用

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

网上有很多博客说@Requestparam 和@RequestBody不能同时使用,这是错误的。根据HTTP协议,并没有说post请求不能带URL参数,经验证往一个带有参数的URL发送post请求也是可以成功的。

         自己个人实际验证结果:

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;

 /*   public List getName() {
        return name;
    }

    public void setName(List name) {
        this.name = name;
    }

    private List name;*/
}

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请求,返回正常:
@RequestBody 和 @RequestParam可以同时使用_第1张图片
body中参数如下:
@RequestBody 和 @RequestParam可以同时使用_第2张图片
        从结果来看,post请求URL带参数是没有问题的,所以@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空异常:
@RequestBody 和 @RequestParam可以同时使用_第3张图片

 
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)
参考文章: https://unmi.cc/why-http-get-cannot-sent-data-with-reuqest-body/

你可能感兴趣的:(Spring,Framework)