SpringMVC异常: Required request body content is missing解析

哈哈 阅读:238 2021-03-31 21:11:27 评论:0

1、项目异常信息:

org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing

2、异常代码片段:

    @ApiOperation(httpMethod = "POST", value = "数据权限信息保存")
    @RequestMapping(value="/insert", method={RequestMethod.POST})
    @ResponseBody
    public Result insert(@RequestBody @ApiParam(name="用户对象", value="json格式对象", required=true) *** entity) ;

3、SpringMVC源代码分析:

@Override
 protected <T> Object readWithMessageConverters(NativeWebRequest webRequest, MethodParameter parameter,
           Type paramType) throws IOException, HttpMediaTypeNotSupportedException, HttpMessageNotReadableException {

        HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
         ServletServerHttpRequest inputMessage = new ServletServerHttpRequest(servletRequest);
 
        Object arg = readWithMessageConverters(inputMessage, parameter, paramType);
          if (arg == null) {
            if (checkRequired(parameter)) {
                throw new HttpMessageNotReadableException("Required request body is missing: " +
                       parameter.getMethod().toGenericString());
            }
        }
         return arg;
    }

    protected boolean checkRequired(MethodParameter parameter) {
       return (parameter.getParameterAnnotation(RequestBody.class).required() && !parameter.isOptional());
   }

  从上述源代码checkRequired方法中可以看出:RequestBody 注解属性required的属性值, parameter.isOptiona判断请求参数是否为空。

public @interface RequestBody {
 
     /**
     * Whether body content is required.
      * <p>Default is {@code true}, leading to an exception thrown in case
      * there is no body content. Switch this to {@code false} if you prefer
      * {@code null} to be passed when the body content is {@code null}.
     * @since 3.2
     */
    boolean required() default true;
 }

从上述代码可以看出:RequestBody注解required的属性值,默认取值为:true.

4、解决办法:@RequestBody(required = false)

 

声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

发表评论
搜索
排行榜
KIKK导航

KIKK导航

关注我们