一.問題描述:
在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請求信息轉換器,配置片段如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<!--- 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數據類型。