1. 程式人生 > >在SpringMVC中使用@RequestBody註解處理json時,報出HTTP Status 415的解決方案

在SpringMVC中使用@RequestBody註解處理json時,報出HTTP Status 415的解決方案

Spring的@RequestBody非常牛x,可以將提交的json直接轉換成POJO物件。

正好今天有這樣的需求,使用一下,結果一直報415,十分頭疼。

HTTP 415 錯誤 – 不支援的媒體型別(Unsupported media type)

我的angularJs是這樣寫的

複製程式碼
$http({method: "POST",
    url: url;
    headers: {'Content-type': 'application/json;charset=UTF-8'},
    data: scope.$modelValue})
.success(function(data, status) {
    
// success handle code }) .error(function(data, status) { // error handle code });
複製程式碼

url與scope.$modelValue都是專案中的程式碼,在這裡佔個坑,scope.$modelValue是一個js物件,會被angularJs轉換成json字串,

反覆看angularJs的文件,又抓包分析,確認js沒有問題。

在網上一查貌似是Spring的問題,有的網友說需要在*-servlet.xml中增加<mvc:annotation-driven />,一看我的專案沒加,立刻加上。

當然還需要加上mvc的xml名稱空間,否則該配置無法解析。

xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"

<mvc:annotation-driven />會自動註冊DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter兩個bean

AnnotationMethodHandlerAdapter將會初始化7個轉換器,可以通過呼叫AnnotationMethodHandlerAdapter的getMessageConverts()方法來獲取轉換器的一個集合 List<HttpMessageConverter>

複製程式碼
ByteArrayHttpMessageConverter 
StringHttpMessageConverter 
ResourceHttpMessageConverter 
SourceHttpMessageConverter 
XmlAwareFormHttpMessageConverter 
Jaxb2RootElementHttpMessageConverter 
MappingJacksonHttpMessageConverter
複製程式碼

對於json的解析就是通過MappingJacksonHttpMessageConverter轉換器完成的。

只新增<mvc:annotation-driven />還不行,需要在classpath環境中能找到Jackson包,用maven配置如下

複製程式碼
 <dependency>  
        <groupId>org.codehaus.jackson</groupId>  
        <artifactId>jackson-mapper-asl</artifactId>  
        <version>1.9.8</version>  
        <type>jar</type>  
        <scope>compile</scope>  
 </dependency>  
複製程式碼

至此問題解決,附上Spring程式碼

複製程式碼
@RequestMapping(value = "/testjson", method = RequestMethod.POST, consumes = "application/json")
@ResponseBody
public void testJson(@RequestBody JsonInfo jsonInfo,
    HttpServletRequest request, HttpServletResponse response)
{
    //handle jsonInfo object instance
}
複製程式碼

 從下文得到幫助,對作者表示感謝:)

http://snowolf.iteye.com/blog/1628861