Springboot--springmvc Required request body content is missing异常

时间:2025-03-21 09:21:00

1.异常

: Required request body is missing

2.问题复现:

@RequestMapping(value = "/somewhere", method = POST)
public SomeResponse someHandler(@RequestBody XXXDTO xxxDTO) { ... }

当入参DTO对象为空时,
@RequestBody对应http请求body,当请求body为空时,异常!
: Required request body is missing: public <<>> ()
        at (:154)
        at (:128)
        at (:121)
        at (:158)
        at (:128)
        at (:97)
        at (:827)
        at (:738)
        at (:85)
        at (:967)
        at (:901)
        at (:970)
        at (:872)
        at (:661)
        at (:846)
        at (:742)
        at (:231)
        at (:166)
        at (:52)
        at (:193)
        at (:166)
        at (:55)
        at (:107)

 1 @Override
 2     protected <T> Object readWithMessageConverters(NativeWebRequest webRequest, MethodParameter parameter,
 3             Type paramType) throws IOException, HttpMediaTypeNotSupportedException, HttpMessageNotReadableException {
 4 
 5         HttpServletRequest servletRequest = (HttpServletRequest.class);
 6         ServletServerHttpRequest inputMessage = new ServletServerHttpRequest(servletRequest);
 7 
 8         Object arg = readWithMessageConverters(inputMessage, parameter, paramType);
 9         if (arg == null) {
10             if (checkRequired(parameter)) {
11                 throw new HttpMessageNotReadableException("Required request body is missing: " +
12                         ().toGenericString());
13             }
14         }
15         return arg;
16     }
17 
18     protected boolean checkRequired(MethodParameter parameter) {
19         return ((RequestBody.class).required() && !());
20     }

看上图,最终是RequestBody注解的required属性。!()代表是否支持null,如果参数类型支持null,则是false,最终不用校验required.

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

看上图,默认是true.我们只需要@RequestBody (required=false)

3.解决方案:

1)@RequestBody (required=false)

 

2) 不要让DTO对象为空