@RequestBody对象为空,异常Required request body is missing的解决办法
发布于 2022-09-05    9,516 次阅读
     由于与前端交互的过程当中,都是用json数据与前端进行交互,这样想取出整个传送过来的json数据的时候,就需要用到@RequestBody这个注解,前端发送数据的格式如下: //测试发送json数据 $("#id").click(function () { $.ajax({ type: "post", url: "test", contentType: "application/json...

     由于与前端交互的过程当中,都是用json数据与前端进行交互,这样想取出整个传送过来的json数据的时候,就需要用到@RequestBody这个注解,前端发送数据的格式如下:

//测试发送json数据 $("#id").click(function () { $.ajax({ type: "post", url: "test", contentType: "application/json; charset=utf-8", data: JSON.stringify(getTestJson()), dataType: "json", success: function (data) { alert(data); }, error:function (XMLHttpRequest, textStatus, errorThrown) { alert(XMLHttpRequest.status); alert(XMLHttpRequest.readyState); alert(textStatus); } }); function getTestJson() { var Json = { "a":"aaaaaaa", "b":0, "c":2, }; return Json; } });

 
    前台的AJAX这样去写,这样传输数据,那么后台就可以拿到完整的数据了,具体怎么拿看如下代码:
@RequestMapping(value = "/test",method = RequestMethod.POST)
    @ResponseBody
    public String test(@RequestBody String requestJson){
            if(requestJson==null||requestJson==""){
                return ApiResponse.buildFailResponse(ResultConstant.OPERATOR_FAIL,"请求接口需要传递正确的JSON数据");
            }
}
这样,加上一个@RequestBody注解,就可以轻松的把请求过来的json数据全部拿到,然后就随便你把json数据是转成
JSONObject还是普通的JAVA对象进行操作了。
    但是,我们在传输json数据的时候,假如json数据为空,那么就会报一个错误,就是Required request body is missing
这个的意思就是我们这个接口必须要传输json格式的数据,假如没有数据,就会报错返回错误的信息。
    但是,我们一般想做的样子是我们由自己去判断数据是否为空,假如为空,返回我们与前端约定格式的数据,那样会
方便前端来进行调试。
    假如不想让系统报错,那么就需要在@RequestBody增加一个Required属性了,并且把该属性设置为false,如下:
 @RequestMapping(value = "/test",method = RequestMethod.POST)
    @ResponseBody
    public String test(@RequestBody(required = false) String requestJson){
            if(requestJson==null||requestJson==""){
                return ApiResponse.buildFailResponse(ResultConstant.OPERATOR_FAIL,"请求接口需要传递正确的JSON数据");
            }
}



 
 

版权说明 : 本文为转载文章, 版权为原作者所有

原文标题 : @RequestBody对象为空,异常Required request body is missing的解决办法

原文连接 : https://blog.csdn.net/qq_38455201/article/details/78952511