SpringMVC @RequestBody 为null问题的排查及解决

 更新时间:2021年10月22日 09:41:08   作者:疯狂哈丘  
这篇文章主要介绍了SpringMVC @RequestBody 为null问题的排查及解决,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

SpringMVC @RequestBody为null

今天写一个springmvc接口,希望入参为json,然后自动转成自己定义的封装对象,于是有了下面的代码

@PostMapping("/update")
@ApiOperation("更新用户信息")
public CumResponseBody update(@RequestBody UserInfoParam param) {
     int userId = getUserId();
     userService.updateUserInfo(userId, param);
     return ResponseFactory.createSuccessResponse("ok");
}
//UserInfoParam.java
public class UserInfoParam {
    private String tel;
    private String email;
    public String getTel() {
        return tel;
    }
    public void setTel(String tel) {
        this.tel = tel;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
}

程序正常启动后,使用swaggerUI发起测试

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{ \ 
   "email": "12%40mail.com", \ 
   "tel": "13677682911" \ 
 }' 'http://127.0.0.1:9998/api/user/update'

最后程序报错

org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public com.pingguiyuan.shop.common.response.CumResponseBody com.pingguiyuan.shop.weixinapi.controller.UserController.update(com.pingguiyuan.shop.common.param.weixin.UserInfoParam)

对了几遍,接口的编写和请求内容都确定没有问题,但是请求的json就是没注入进来转成param对象。查了一圈资料也没找到满意的答案,就只能给springMVC的源码打断点跟一遍,看一下具体是哪里出了问题。

由于本篇不是介绍springMVC实现原理的,就不具体介绍springMVC的源码。

最后断点发现springMVC从request的inputstream没取出内容来(inputstream.read()出来的直接是-1)。由于有在一个拦截器输出请求的参数内容—>【当请求时get时,通过request.getParameterMap();获取参数,当请求时post时,则是直接输出request的inpustream里面的内容】。所以请求的body里面是肯定有内容的,也就是说request.getInputstream()的流是有内容的,那为什么到springMVC这read出来的就是-1呢。

稍微理了下思路,发现是自己给自己挖了个坑。答案是:request的inputstream只能读一次,博主在拦截器中把inputstream的内容都输出来了,到springMVC这,就没有内容可以读了。

关于inputsteam的一些理解

servlet request的inpustream是面向流的,这意味着读取该inputstream时是一个字节一个字节读的,直到整个流的字节全部读回来,这期间没有对这些数据做任何缓存。因此,整个流一旦被读完,是无法再继续读的。

这和nio的处理方式就完全不同,如果是nio的话,数据是先被读取到一块缓存中,然后程序去读取这块缓存的内容,这时候就允许程序重复读取缓存的内容,比如mark()然后reset()或者直接clear()重新读。

特意去看了下InputStream的源码,发现其实是有mark()和reset()方法的,但是默认的实现表示这是不能用的,源码如下

public boolean markSupported() {
    return false;
}
public synchronized void reset() throws IOException {
        throw new IOException("mark/reset not supported");
}
public synchronized void mark(int readlimit) {}

其中mark是一个空函数,reset函数直接抛出异常。同时,inputstream还提供了markSupported()方法,默认是返回false,表示不支持mark,也就是标记(用于重新读)。

但是并不是所有的Inputstream实现都不允许重复读,比如BufferedInputStream就是允许重复读的,从类名来看,就知道这个类其实就是将读出来的数据进行缓存,来达到可以重复读的效果。下面是BufferedInputStream重写的3个方法

    public synchronized void mark(int readlimit) {
        marklimit = readlimit;
        markpos = pos;
    }
    public synchronized void reset() throws IOException {
        getBufIfOpen(); // Cause exception if closed
        if (markpos < 0)
            throw new IOException("Resetting to invalid mark");
        pos = markpos;
    }
    public boolean markSupported() {
        return true;
    }

可以看到BufferedInputStream的markSupported()方法返回的是true,说明它应该是支持重复读的。我们可以通过mark()和reset()来实现重复读的效果。

@RequestBody 自动映射原理的简单介绍

springMVC在处理请求时,先找到对应controller处理该请求的方法,然后遍历整个方法的所有参数,进行封装。在处理参数的过程中,会调用AbstractMessageConverterMethodArgumentResolver#readWithMessageConverters()类的方法进行进行一些转换操作,源码如下

protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage, MethodParameter parameter,
            Type targetType) throws IOException, HttpMediaTypeNotSupportedException, HttpMessageNotReadableException {
        MediaType contentType;
        boolean noContentType = false;
        try {
            contentType = inputMessage.getHeaders().getContentType();
        }
        catch (InvalidMediaTypeException ex) {
            throw new HttpMediaTypeNotSupportedException(ex.getMessage());
        }
        if (contentType == null) {
            noContentType = true;
            contentType = MediaType.APPLICATION_OCTET_STREAM;
        }
        Class<?> contextClass = parameter.getContainingClass();
        Class<T> targetClass = (targetType instanceof Class ? (Class<T>) targetType : null);
        if (targetClass == null) {
            ResolvableType resolvableType = ResolvableType.forMethodParameter(parameter);
            targetClass = (Class<T>) resolvableType.resolve();
        }
        HttpMethod httpMethod = (inputMessage instanceof HttpRequest ? ((HttpRequest) inputMessage).getMethod() : null);
        Object body = NO_VALUE;
        EmptyBodyCheckingHttpInputMessage message;
        try {
            message = new EmptyBodyCheckingHttpInputMessage(inputMessage);
            for (HttpMessageConverter<?> converter : this.messageConverters) {
                Class<HttpMessageConverter<?>> converterType = (Class<HttpMessageConverter<?>>) converter.getClass();
                GenericHttpMessageConverter<?> genericConverter =
                        (converter instanceof GenericHttpMessageConverter ? (GenericHttpMessageConverter<?>) converter : null);
                if (genericConverter != null ? genericConverter.canRead(targetType, contextClass, contentType) :
                        (targetClass != null && converter.canRead(targetClass, contentType))) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Read [" + targetType + "] as \"" + contentType + "\" with [" + converter + "]");
                    }
                    if (message.hasBody()) {
                        HttpInputMessage msgToUse =
                                getAdvice().beforeBodyRead(message, parameter, targetType, converterType);
                        body = (genericConverter != null ? genericConverter.read(targetType, contextClass, msgToUse) :
                                ((HttpMessageConverter<T>) converter).read(targetClass, msgToUse));
                        body = getAdvice().afterBodyRead(body, msgToUse, parameter, targetType, converterType);
                    }
                    else {
                        body = getAdvice().handleEmptyBody(null, message, parameter, targetType, converterType);
                    }
                    break;
                }
            }
        }
        catch (IOException ex) {
            throw new HttpMessageNotReadableException("I/O error while reading input message", ex);
        }
        if (body == NO_VALUE) {
            if (httpMethod == null || !SUPPORTED_METHODS.contains(httpMethod) ||
                    (noContentType && !message.hasBody())) {
                return null;
            }
            throw new HttpMediaTypeNotSupportedException(contentType, this.allSupportedMediaTypes);
        }
        return body;
    }

上面这段代码主要做的事情大概就是获取请求的contentType,然后遍历配置的HttpMessageConverter—>this.messageConverters,如果该HttpMessageConverter可以用于解析这种contentType(genericConverter.canRead方法),就用这种HttpMessageConverter解析请求的请求体内容,最后返回具体的对象。

在spring5.0.7版本中,messageConverters默认似乎配置了8种convert。分别是

  • ByteArrayMessageConverter
  • StringHttpMessageConverter
  • ResourceHttpMessageConverter
  • ResourceRegionHttpMessageConverter
  • SourceHttpMessageConverter
  • AllEncompassingFormHttpMessageConverter
  • MappingJackson2HttpMessageConverter
  • Jaxb2RootElementHttpMessageConverter

具体的convert是哪些contentType并怎么解析的,这里不多做介绍,感兴趣的朋友可以自行查看源码。

比如我们请求的header中的contentType是application/json,那么在遍历messageConverters的时候,其他genericConverter.canRead()都会返回false,说明没有适配上。

然后遍历到MappingJackson2HttpMessageConverter时genericConverter.canRead()返回true,接着就去获取请求的请求体,并通过json解析成我们@RequestBody定义的对象。

因此,如果我们的请求的contentType和数据协议都是自定义的,我们完全可以自己实现一个HttpMessageConverter,然后解析特定的contentType。

最后记得将这个实现放入messageConverters中,这样springMVC就会自动帮我们把请求内容解析成对象了。

关于@requestBody的一些说明

1、@requestBody注解

常用来处理content-type不是默认的application/x-www-form-urlcoded编码的内容,比如说:application/json或者是application/xml等。一般情况下来说常用其来处理application/json类型。

2、通过@requestBody

可以将请求体中的JSON字符串绑定到相应的bean上,当然也可以将其分别绑定到对应的字符串上。

例如说以下情况:

$.ajax({       
         url:"/login",       
         type:"POST",        
          data:'{"userName":"admin","pwd","admin123"}',      
        content-type:"application/json charset=utf-8",        
          success:function(data)
             {          
                alert("request success ! ");       
            }    
});
@requestMapping("/login")    
  public void login(@requestBody String userName,@requestBody String pwd){      
  System.out.println(userName+" :"+pwd);    
}

这种情况是将JSON字符串中的两个变量的值分别赋予了两个字符串,但是呢假如我有一个User类,拥有如下字段:

String userName;
String pwd;

那么上述参数可以改为以下形式:@requestBody User user 这种形式会将JSON字符串中的值赋予user中对应的属性上

需要注意的是,JSON字符串中的key必须对应user中的属性名,否则是请求不过去的。

3、在一些特殊情况

@requestBody也可以用来处理content-type类型为application/x-www-form-urlcoded的内容,只不过这种方式不是很常用,在处理这类请求的时候,@requestBody会将处理结果放到一个MultiValueMap<String,String>中,这种情况一般在特殊情况下才会使用,例如jQuery easyUI的datagrid请求数据的时候需要使用到这种方式、小型项目只创建一个POJO类的话也可以使用这种接受方式。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Java中的WeakHashMap简析

    Java中的WeakHashMap简析

    这篇文章主要介绍了Java中的WeakHashMap简析,Map 的子类常见的有 HashMap、Hashtable、ConcurrentHashMap、LinkedHashMap 等,WeakHashMap,直译就是,虚弱的 HashMap,从名字可得知其和 HashMap 有关,需要的朋友可以参考下
    2023-09-09
  • SpringCloud-Hystrix组件使用方法

    SpringCloud-Hystrix组件使用方法

    这篇文章主要介绍了SpringCloud-Hystrix组件使用方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-12-12
  • Spring Boot 中的自动配置autoconfigure详解

    Spring Boot 中的自动配置autoconfigure详解

    这篇文章主要介绍了Spring Boot 中的自动配置autoconfigure详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
    2024-01-01
  • 如何从官网下载Hibernate jar包的方法示例

    如何从官网下载Hibernate jar包的方法示例

    这篇文章主要介绍了如何从官网下载Hibernate jar包的方法示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-04-04
  • JavaEE中用response向客户端输出中文数据乱码问题分析

    JavaEE中用response向客户端输出中文数据乱码问题分析

    这篇文章主要介绍了JavaEE中用response向客户端输出中文数据乱码问题分析,需要的朋友可以参考下
    2014-10-10
  • Java 后端开发中Tomcat服务器运行不了的五种解决方案

    Java 后端开发中Tomcat服务器运行不了的五种解决方案

    tomcat是在使用Java编程语言开发服务端技术使用最广泛的服务器之一,但经常在开发项目的时候会出现运行不了的情况,这里总结出几种能解决的办法
    2021-10-10
  • java 获取服务器真实IP的实例

    java 获取服务器真实IP的实例

    这篇文章主要介绍了java 获取服务器真实IP的实例的相关资料,这里提供实现方法帮助大家学习理解这部分内容,需要的朋友可以参考下
    2017-08-08
  • SpringBoot中的统一异常处理详细解析

    SpringBoot中的统一异常处理详细解析

    这篇文章主要介绍了SpringBoot中的统一异常处理详细解析,该注解可以把异常处理器应用到所有控制器,而不是单个控制器,借助该注解,我们可以实现:在独立的某个地方,比如单独一个类,定义一套对各种异常的处理机制,需要的朋友可以参考下
    2024-01-01
  • Java超详细教你写一个学籍管理系统案例

    Java超详细教你写一个学籍管理系统案例

    这篇文章主要介绍了怎么用Java来写一个学籍管理系统,学籍管理主要涉及到学生信息的增删查改,本篇将详细的实现,感兴趣的朋友跟随文章往下看看吧
    2022-03-03
  • Java Scanner输入两个数组的方法

    Java Scanner输入两个数组的方法

    今天小编就为大家分享一篇Java Scanner输入两个数组的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-07-07

最新评论