SpringMVC 中HttpMessageConverter简介和Http请求415 的问题
一.问题描述:
在sprinvmvc的web程序中,我在页面发送ajax 的post请求,然后在服务器端利用@requestbody接收请求body中的参数,当时运行过程中,我想服务器发送ajax请求,浏览器一直反馈415 unsupported media type或者400的状态码,以为是ajax写的有问题。便查找了半天资料,才发现spring-mvc.config文件的配置中少了东西,当然也有可能是你真的在ajax中缺少了对content-type参数的设置。分析后应该是我springmvc-config.xml文件配置有问题。
(注):400:(错误请求) 服务器不理解请求的语法。 415:(不支持的媒体类型) 请求的格式不受请求页面的支持。
二.解决方法:
在springmvc-config.xml文件中,增加了一个stringhttpmessageconverter请求信息转换器,配置片段如下:
<!--- stringhttpmessageconverter bean --> < bean id = "stringhttpmessageconverter" class = "org.springframework.http.converter.stringhttpmessageconverter"/> <!-- 启动spring mvc的注解功能,完成请求和注解pojo的映射 --> < bean class ="org.springframework.web.servlet.mvc.annotation.annotationmethodhandleradapter" > < property name= "messageconverters" > < list> < ref bean= "mappingjacksonhttpmessageconverter" /> <!-- 新增的stringmessageconverter bean--> < ref bean= "stringhttpmessageconverter" /> < ref bean= "jsonhttpmessageconverter" /> < ref bean= "formhttpmessageconverter" /> </ list> </ property> </ bean>
三.httpmessageconverter请求信息转换器简介:
httpmessageconverter接口指定了一个可以把http request信息和http response信息进行格式转换的转换器。通常实现httpmessageconverter接口的转换器有以下几种:
bytearrayhttpmessageconverter: 负责读取二进制格式的数据和写出二进制格式的数据;
stringhttpmessageconverter: 负责读取字符串格式的数据和写出二进制格式的数据;
resourcehttpmessageconverter:负责读取资源文件和写出资源文件数据;
formhttpmessageconverter: 负责读取form提交的数据(能读取的数据格式为 application/x-www-form-urlencoded,不能读取multipart/form-data格式数据);负责写入application/x-www-from-urlencoded和multipart/form-data格式的数据;
mappingjacksonhttpmessageconverter: 负责读取和写入json格式的数据;
sourcehttpmessageconverter: 负责读取和写入 xml 中javax.xml.transform.source定义的数据;
jaxb2rootelementhttpmessageconverter: 负责读取和写入xml 标签格式的数据;
atomfeedhttpmessageconverter: 负责读取和写入atom格式的数据;
rsschannelhttpmessageconverter: 负责读取和写入rss格式的数据;
更多关于httpmessageconverter的信息请看:
http://docs.spring.io/spring/docs/3.0.x/api/org/springframework/http/converter/httpmessageconverter.html
四.httpmessageconverter请求信息转换器执行流程:
当用户发送请求后,@requestbody 注解会读取请求body中的数据,默认的请求转换器httpmessageconverter通过获取请求头header中的content-type来确认请求头的数据格式,从而来为请求数据适配合适的转换器。例如contenttype:applicatin/json,那么转换器会适配mappingjacksonhttpmessageconverter。响应时候的时候同理,@responsebody注解会启用httpmessageconverter,通过检测header中accept属性来适配的响应的转换器。
总结:
当在使用springmvc做服务器数据接收时,尤其是在做ajax请求的时候,尤其要注意contenttype属性,和accepte 属性的设置,在springmvc-config.xml中配置好相应的转换器。当我们在用springmvc做 ajax 请求的时候,有的做法用response.getwriter().print()的方法,还有更好的方法就是添加@responsebody注解,直接返回map类型的数据,转换器自动转换为json数据类型。