@RequestBody的作用

@RequestBody用于读取Request请求的body数据,然后利用SpringMVC配置的HttpMessageConverter对数据进行转换,最后把转换后的数据绑定到被@RequestBody注解的参数上;

@RequestBody的使用场景

根据request header中 Content-Type和被@RequestBody注解的参数不同,最常见的应用场景如下:

  1.  Content-Type为application/json

    • 参数为JavaBean:可实现json反序列化为JavaBean,使用的HttpMessageConverter为 MappingJackson2HttpMessageConverter
    • 参数为String:简单将字符串赋值给参数,使用的HttpMessageConverter为 StringHttpMessageConverter
  2.  Content-Type为application/xml
    • 参数为JavaBean可实现xml反序列化为JavaBean,使用的HttpMessageConverter为 Jaxb2RootElementHttpMessageConverter
    • 参数为String:简单将字符串赋值给参数,使用的HttpMessageConverter为 StringHttpMessageConverter
  3. application/x-www-form-urlencoded
    • 参数为String:简单将字符串赋值给参数,使用的HttpMessageConverter为 StringHttpMessageConverter

HttpMessageConverter接口

该接口定义了五个方法,分别是读取数据时的 canRead()、read() ,写入数据时的canWrite()、 write()方法以及获取支持类型的 getSupportedMediaTypes()

public interface HttpMessageConverter<T> {
// Indicate whether the given class and media type can be read by this converter.
boolean canRead(Class<?> clazz, MediaType mediaType);
// Indicate whether the given class and media type can be written by this converter.
boolean canWrite(Class<?> clazz, MediaType mediaType);
// Return the list of MediaType objects supported by this converter.
List<MediaType> getSupportedMediaTypes();
// Read an object of the given type from the given input message, and returns it.
T read(Class<T> clazz, HttpInputMessage inputMessage) throws IOException,
HttpMessageNotReadableException;
// Write an given object to the given output message.
void write(T t, HttpOutputMessage outputMessage) throws IOException,
HttpMessageNotWritableException;
}

使用 <mvc:annotation-driven />标签配置时,默认配置了RequestMappingHandlerAdapter,并为他配置了一下默认的HttpMessageConverter:

  1. ByteArrayHttpMessageConverter: 负责读取二进制格式的数据和写出二进制格式的数据;
  2. StringHttpMessageConverter:   负责读取字符串格式的数据和写出二进制格式的数据;
  3. ResourceHttpMessageConverter:负责读取资源文件和写出资源文件数据;
  4. FormHttpMessageConverter:       负责读取form提交的数据(能读取的数据格式为 application/x-www-form-urlencoded,不能读取multipart/form-data格式数据);负责写入application/x-www-from-urlencoded和multipart/form-data格式的数据;
  5. MappingJacksonHttpMessageConverter:  负责读取和写入json格式的数据;
  6. SouceHttpMessageConverter:                   负责读取和写入 xml 中javax.xml.transform.Source定义的数据;
  7. Jaxb2RootElementHttpMessageConverter:  负责读取和写入xml 标签格式的数据;
  8. AtomFeedHttpMessageConverter:              负责读取和写入Atom格式的数据;
  9. RssChannelHttpMessageConverter:           负责读取和写入RSS格式的数据;

HttpMessageConverter匹配过程

根据Request对象header部分的ContentType类型和被注解参数类型,逐一匹配合适的HttpMessageConverter来读取数据;

    protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage, MethodParameter parameter,
Type targetType) throws IOException, HttpMediaTypeNotSupportedException, HttpMessageNotReadableException {
......
MediaType contentType;
contentType = inputMessage.getHeaders().getContentType();
....... for (HttpMessageConverter<?> converter : this.messageConverters) {
Class<HttpMessageConverter<?>> converterType = (Class<HttpMessageConverter<?>>) converter.getClass();
if (converter instanceof GenericHttpMessageConverter) {
GenericHttpMessageConverter<?> genericConverter = (GenericHttpMessageConverter<?>) converter;
if (genericConverter.canRead(targetType, contextClass, contentType)) {
if (logger.isDebugEnabled()) {
logger.debug("Read [" + targetType + "] as \"" + contentType + "\" with [" + converter + "]");
}
if (inputMessage.getBody() != null) {
inputMessage = getAdvice().beforeBodyRead(inputMessage, parameter, targetType, converterType);
body = genericConverter.read(targetType, contextClass, inputMessage);
body = getAdvice().afterBodyRead(body, inputMessage, parameter, targetType, converterType);
}
else {
body = getAdvice().handleEmptyBody(null, inputMessage, parameter, targetType, converterType);
}
break;
}
}
else if (targetClass != null) {
if (converter.canRead(targetClass, contentType)) {
if (logger.isDebugEnabled()) {
logger.debug("Read [" + targetType + "] as \"" + contentType + "\" with [" + converter + "]");
}
if (inputMessage.getBody() != null) {
inputMessage = getAdvice().beforeBodyRead(inputMessage, parameter, targetType, converterType);
body = ((HttpMessageConverter<T>) converter).read(targetClass, inputMessage);
body = getAdvice().afterBodyRead(body, inputMessage, parameter, targetType, converterType);
}
else {
body = getAdvice().handleEmptyBody(null, inputMessage, parameter, targetType, converterType);
}
break;
}
}
}
....... return body;
}

注意

  1. 在一个方法的参数列表中,@RequestBody只能使用一次;
  2. json字符串中,如果value为""的话,后端对应属性如果是String类型的,那么接受到的就是"",如果是后端属性的类型是Integer、Double等类型,那么接收到的就是null;
  3. json字符串中,如果value为null的话,后端对应收到的就是null;
  4. 在传json字符串给后端时,如果某个key没有value的话,要么干脆就不写该key,要么就将value赋值null  或"",不能有类似 {......,"key":,.....}, 这样的写法

SpringMVC @RequestBody的使用的更多相关文章

  1. SpringMVC @RequestBody接收Json对象字符串 demo

    springmvc 的这个 @RequestBody 用得比较少,今天看了一下,还是很方便. @RequestBody 接收类似 [{name: "test"}, {name: & ...

  2. SpringMVC @RequestBody请求参数在postman中的请求

    使用SpringMVC框架,controller使用参数  @RequestBody  LoginReq req   注解方式模拟http请求 需要请求header添加一个参数 设置  Header参 ...

  3. SpringMVC @RequestBody 自动转json Http415错误

    转自: http://blog.csdn.net/tiantiandjava/article/details/46125141 项目中想用@RequestBody直接接收json串转成对象 网上查了使 ...

  4. SpringMVC @RequestBody接收Json对象字符串

    其实 @RequestBody接收的是一个Json对象的字符串,而不是一个Json对象.然而在ajax请求往往传的都是Json对象,后来发现用 JSON.stringify(data)的方式就能将对象 ...

  5. SpringMVC@RequestBody小细节

    关于@RequestBody  参数类型自己的包装类,还是类似String/int,区别: 1.@RequestBody LoginParmar parmar String user_number = ...

  6. SpringMVC @RequestBody @RequestParam @PathVariable 等参数绑定注解详解

    request 数据到handler method 参数数据的绑定所用到的注解和什么情形下使用: http://blog.csdn.net/walkerjong/article/details/794 ...

  7. SpringMVC @RequestBody 接收Json数组对象

    @RequestMapping(value="/signIn",method=RequestMethod.POST) public int saveUser(@RequestBod ...

  8. SpringMVC @RequestBody问题:Unrecognized field , not marked as ignorable

    http://blog.csdn.net/isea533/article/details/33397735

  9. 【Spring学习笔记-MVC-6】SpringMVC 之@RequestBody 接收Json数组对象

    作者:ssslinppp       1. 摘要 程序流程: 前台使用ajax技术,传递json字符串到后台: 后台使用Spring MVC注解@RequestBody 接受前台传递的json字符串, ...

随机推荐

  1. matlab:inv,pinv逆与伪逆

    对于方阵A,如果为非奇异方阵,则存在逆矩阵inv(A)对于奇异矩阵或者非方阵,并不存在逆矩阵,但可以使用pinv(A)求其伪逆   inv:   inv(A)*B实际上可以写成A\BB*inv(A)实 ...

  2. WebSocket原理与实践(二)---WebSocket协议

    WebSocket原理与实践(二)---WebSocket协议 WebSocket协议是为了解决web即时应用中服务器与客户端浏览器全双工通信问题而设计的.协议定义ws和wss协议,分别为普通请求和基 ...

  3. centos7搭建elasticsearch

    Elasticsearch:负责日志检索和分析,它的特点有:分布式,零配置,自动发现,索引自动分片,索引副本机制,restful风格接口,多数据源,自动搜索负载等 Logstash:对日志进行收集.过 ...

  4. MySQL(三)用正则表达式搜索

    正则表达式是用来匹配文本的特殊的串(字符集合),将一个模式(正则表达式)与一个文本串进行比较: 所有种类的程序设计语言.文本编辑器.操作系统等都支持正则表达式,正则表达式用正则表达式语言来建立: My ...

  5. C#中的位的或运算的理解

    如果懂位的运算,看到下面这2个程序执行的结果,会很容易理解,如果像我这样的菜鸟,刚接触开始肯定也觉得晕晕的,|= 这是什么运算符? |=就是位的或运算符,下面还是用上面的程序来讲解一下,为什么上面2个 ...

  6. ORA-10858:在要求输入数字处找到非数字字符

    今天在写sql语句的时候,运行报错:ORA-10858:在要求输入数字处找到非数字字符 在网上查了一下为什么会有这种错误,有一个建议是可能是写的sql语句中的日期没有处理.仔细看了一下自己写的代码 就 ...

  7. Dell Technology Summit(2018.10.17)

    时间:2018.10.17地点:北京国家会议中心

  8. Artificial Intelligence Computing Conference(2018.09.12)

    时间:2018.09.12地点:北京国际饭店会议中心

  9. Task 异步编程测试案例及基础应用说明

    对于多线程,我们经常使用的是Thread.在我们了解Task之前,如果我们要使用多核的功能可能就会自己来开线程,然而这种线程模型在.net 4.0之后被一种称为基于“任务的编程模型”所冲击,因为tas ...

  10. .Net架构篇:思考如何设计一款实用的分布式监控系统?

    前言 无论从最早期的unix操作系统,还是曾经大行其道的单体式应用,还是现在日益流行的微服务架构,始终都离不开监控的身影.如windows的任务管理器,linux的top命令,都可以看作是监控的面板. ...