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