@RequestBody与Content-type

https://www.jianshu.com/p/6a83b73060bb

作者:沈渊
链接:https://www.jianshu.com/p/6a83b73060bb
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

1、简介

Spring Web MVC 是一种基于Java的实现了Web MVC设计模式的请求驱动类型的轻量级Web框架,自Spring MVC出现以来,Java服务端开发逐渐采用Spring MVC编写Http接口。今天主要跟大家分享一个 @RequestBody 与 application/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:

 
  1. @RequestMapping(value = "/alarm/send", method = RequestMethod.POST)

  2. public ResponseEntity<String> sendAlarm1(@RequestBody MessageAlarmReq req) {

  3. boolean success = false;

  4. System.out.println(req);

  5. return new ResponseEntity<String>(HttpStatus.OK);

  6. }

其中,MessageAlarmReq定义:

 
  1. @Data

  2. public class MessageAlarmReq {

  3. private String msgObject;

  4. private String msgTitle;

  5. private String msgContent;

  6. private String msgLevel;

  7. private String msgSource;

  8. private String msgSenders;

  9. private String msgReceivers;

  10. }

本希望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这种格式:

 
  1. private List<MediaType> supportedMediaTypes = new ArrayList();

  2. this.supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);

  3. this.supportedMediaTypes.add(MediaType.MULTIPART_FORM_DATA);

  4.  
  5. 其中:

  6. MediaType APPLICATION_FORM_URLENCODED = valueOf("application/x-www-form-urlencoded");

  7. MediaType MULTIPART_FORM_DATA = valueOf("multipart/form-data");

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

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

  2.  

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

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

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

4、解决方案

方案一、

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

 
  1. @RequestMapping(value = "/alarm/send", method = RequestMethod.POST)

  2. public ResponseEntity<String> sendAlarm1(@RequestBody MultiValueMap<String, String> req) {

  3. boolean success = false;

  4. System.out.println(req);

  5. return new ResponseEntity<String>(HttpStatus.OK);

  6. }

这样就能符合FormHttpMessageConverter的要求。

方案二、

使用ModelAttribute:

 
  1. @RequestMapping(value = "/alarm/send", method = RequestMethod.POST)

  2. public ResponseEntity<String> sendAlarm1(@ModelAttribute("alarmReq") MessageAlarmReq req)

  3. { ...... }

  4.  
  5. @ModelAttribute("alarmReq")

  6. public MessageAlarmReq getMessageAlarmReq() {

  7. return new MessageAlarmReq();

  8. }

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

5、相关问题

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

 
  1. @RequestMapping(value = "/alarm/send", method = RequestMethod.POST)

  2. public ResponseEntity<String> sendAlarm1(MessageAlarmReq req) {

  3. boolean success = false;

  4. System.out.println(req);

  5. return new ResponseEntity<String>(HttpStatus.OK);

  6. }

此处暂时还没找到具体原因,因为项目用的是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的方式,因为目前具体原因不明,不排除未来有其他坑的可能。


 

猜你喜欢

转载自blog.csdn.net/weixin_41649568/article/details/85259936