本打算今天早點下班,結果下午測試調試程序發現一個問題糾結到晚上才解決,現在寫一篇博客來總結下。
是這樣的,本人在Spring mvc控制層用到了@ResponseBody標注,以便返回的數據為json格式的數據,到前端JS中用。
問題來了,當我用火狐調試發現請求總是報:406 Not Acceptable,message:description The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ()錯誤。(說是指定的資源已經找到,但它的MIME類型和客戶在Accpet頭中所指定的不兼容)。
於是樓主那個糾結,那個郁悶啊。BUG了又BUG,百度了又百度,又懷疑是引用的ext.js文件有問題,因為報ext.base和ext.all語法錯誤。最后發現是mime類型不匹配。由於我要返回的是json數據,而瀏覽器接受的是text/html;charset=UTF-8文本類型。不過發現問題還有好幾個,一一解決之:
- 未在pom文件中引入json的轉換包。需要引入如下2個包:
<!-- jackson start --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-lgpl</artifactId> <version>1.9.12</version> </dependency> <!-- jackson end -->
2. spring-servlet.xml文件中需要配置轉換的bean
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <util:list id="beanList"> <ref bean="mappingJacksonHttpMessageConverter" /> </util:list> </property> </bean> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean>
3. 最后,別忘了還要聲明util的schema文件和地址,在spring-servlet.xml文件的頭部聲明部分加入如下三行即可
xmlns:util="http://www.springframework.org/schema/util"
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd
OK,搞定,大功告成,下班~~~