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

网友投稿 360 2022-09-21


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

目录SpringMVC @RequestBody为null关于inputsteam的一些理解@RequestBody 自动映射原理的简单介绍关于@requestBody的一些说明1、@requestBody注解2、通过@requestBody3、在一些特殊情况

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

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 targetClass = (targetType instanceof Class ? (Class) targetType : null);

if (targetClass == null) {

ResolvableType resolvableType = ResolvableType.forMethodParameter(parameter);

targetClass = (Class) 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> converterType = (Class>) 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) 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中的contenthttp://Type是application/json,那么在遍历messageConverters的时候,其他genericConverter.canRead()都会返回false,说明没有适配上。

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

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

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

关于@requestBody的一些说明

1、@requestBody注解http://

常用来处理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中,这种情况一般在特殊情况下才会使用,例如jquery easyUI的datagrid请求数据的时候需要使用到这种方式、小型项目只创建一个POJO类的话也可以使用这种接受方式。

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 targetClass = (targetType instanceof Class ? (Class) targetType : null);

if (targetClass == null) {

ResolvableType resolvableType = ResolvableType.forMethodParameter(parameter);

targetClass = (Class) 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> converterType = (Class>) 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) 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中的contenthttp://Type是application/json,那么在遍历messageConverters的时候,其他genericConverter.canRead()都会返回false,说明没有适配上。

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

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

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

关于@requestBody的一些说明

1、@requestBody注解http://

常用来处理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中,这种情况一般在特殊情况下才会使用,例如jquery easyUI的datagrid请求数据的时候需要使用到这种方式、小型项目只创建一个POJO类的话也可以使用这种接受方式。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:生成树协议(三)(三种生成树协议)
下一篇:生成树协议(二)(生成树的协议)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~