@RequestBody与Content-type

1、简介

Spring Web MVC 是一种基于Java的实现了Web MVC设计模式的请求驱动类型的轻量级Web框架,自Spring MVC出现以来,Java服务端开发逐渐采用Spring MVC编写Http接口。今天主要跟大家分享一个 @RequestBodyapplication/x-www-form-urlencoded 同时使用时遇到的坑。

2、问题描述

要发送的HTTP请求:

curl --header 'content-type:application/x-www-form-urlencoded;charset=UTF-8' -d 'msgObject=string&msgTitle=string&msgContent=string&msgLevel=string&msgSource=string&msgSenders=string&msgReceivers=string' 'http://127.0.0.1:8080/service/send'

服务端Controller:

@RequestMapping(value = "/alarm/send", method = RequestMethod.POST)
public ResponseEntity<String> sendAlarm1(@RequestBody MessageAlarmReq req) {
    boolean success = false;
    System.out.println(req);
    return new ResponseEntity<String>(HttpStatus.OK);
}

其中,MessageAlarmReq定义:

@Data
public class MessageAlarmReq {
    private String msgObject;
    private String msgTitle;
    private String msgContent;
    private String msgLevel;
    private String msgSource;
    private String msgSenders;
    private String msgReceivers;
}

本希望Spring MVC将body映射为MessageAlarmReq对象,但实际上得到了:

org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded' not supported

3、问题分析

Spring 3.X系列增加了新注解 @ResponseBody@RequestBody
@RequestBody 将HTTP请求正文转换为适合的HttpMessageConverter对象。
Spring MVC 使用HttpMessageConverter将请求对象转化为我们希望的格式,当我们在方法中加入@RequestBody注解,Spring MVC固定使用RequestMappingHandlerAdapter来解析,其中RequestMappingHandlerAdapter支持的HttpMessageConverter有四种:

ByteArrayHttpMessageConverter:转化 byte arrays.
StringHttpMessageConverter:转化 Strings.
FormHttpMessageConverter:转化 form data to/from a MultiValueMap.
SourceHttpMessageConverter:转化 to/from a javax.xml.transform.Source.

通过分析这四个Converter可知,FormHttpMessageConverter支持解析application/x-www-form-urlencoded这种格式:

private List<MediaType> supportedMediaTypes = new ArrayList();
this.supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
this.supportedMediaTypes.add(MediaType.MULTIPART_FORM_DATA);

其中:
MediaType APPLICATION_FORM_URLENCODED = valueOf("application/x-www-form-urlencoded");
MediaType MULTIPART_FORM_DATA = valueOf("multipart/form-data");

了解HttpMessageConverter原理可知,HttpMessageConverter使用:

T read(Class<? extends T> var1, HttpInputMessage var2) throws IOException, HttpMessageNotReadableException;

将参数转化为我们希望的对象,FormHttpMessageConverter的实现方式为:

public MultiValueMap<String, String> read(@Nullable Class<? extends MultiValueMap<String, ?>> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException{ ...... };

由此,我们可以知道,FormHttpMessageConverter只能将requestBody转化为MultiValueMap,而不能是自定义对象。

4、解决方案

方案一、

将 @RequestBody 参数设置为 MultiValueMap,即 Controller定义修改为:

@RequestMapping(value = "/alarm/send", method = RequestMethod.POST)
public ResponseEntity<String> sendAlarm1(@RequestBody MultiValueMap<String, String> req) {
    boolean success = false;
    System.out.println(req);
    return new ResponseEntity<String>(HttpStatus.OK);
}

这样就能符合FormHttpMessageConverter的要求。

方案二、

使用ModelAttribute:

@RequestMapping(value = "/alarm/send", method = RequestMethod.POST)
public ResponseEntity<String> sendAlarm1(@ModelAttribute("alarmReq") MessageAlarmReq req)
 { ...... }

@ModelAttribute("alarmReq")
public MessageAlarmReq getMessageAlarmReq() {
    return new MessageAlarmReq();
}

利用ModelAttribute进行对象映射,参考文献

5、相关问题

经过测试我发现假如代码中直接删除@RequestBody,也可以实现 RequestBody 直接映射为自定义对象:

@RequestMapping(value = "/alarm/send", method = RequestMethod.POST)
public ResponseEntity<String> sendAlarm1(MessageAlarmReq req) {
    boolean success = false;
    System.out.println(req);
    return new ResponseEntity<String>(HttpStatus.OK);
}

此处暂时还没找到具体原因,因为项目用的是Spring Boot 2.0,推测有可能是Spring Boot做的一些优化。

6、总结

通过上述分析,我们看到在我们使用@RequestBody,享受其便利,增大方法可读性时,无形中也受到RequestMappingHandlerAdapter中HttpMessageConverter的限制,对此个人建议:

  1. 针对新编写的接口,优先使用@RequestBody,前后端传参时尽量使用json格式,增加代码可读性;
  2. 为兼容老版本接口,不要再使用@RequestBody,推荐使用@ModelAttribute,充分利用Spring MVC自带Converter的参数映射,减少代码逻辑;
  3. 如果项目中有很多Content-Type:application/x-www-form-urlencoded的情况,推荐扩展HttpMessageConverter,自己来编码处理对象映射;
  4. 不推荐 5 中描述的直接删除@RequestBody的方式,因为目前具体原因不明,不排除未来有其他坑的可能。
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,941评论 6 342
  • Spring的模型-视图-控制器(MVC)框架是围绕一个DispatcherServlet来设计的,这个Servl...
    alexpdh阅读 2,665评论 0 3
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,869评论 18 139
  • 翻译自Spring官方文档 4.1.2版本 相关文章: Spring参考手册 1 Spring Framework...
    liycode阅读 710评论 0 2
  • 现在想来,生活在某些方面确实是公平的。我们经常怨天尤人,抱怨自我不幸, 却并未察觉在不幸的另一面竟然是大大的万幸...
    给你一嘴巴丫子的乔治阅读 1,254评论 0 1