一、概述:
本文介紹且記錄如何解決在SpringMVC 中遇到415 Unsupported Media Type 的問題,并且順便介紹Spring MVC的HTTP請求資訊轉換器
HttpMessageConverter
。
二、問題描述:
在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資料類型。
作者:Ziv小威
出處:http://imziv.com/
關于作者:專注于Java技術的程式員一枚,此外對JS開發保持着較高的興趣。愛好音樂,閱讀,FM等等。
本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接配接。
如有問題,可以郵件:[email protected]
微網誌:Ziv小威