@ResponseBody返回JSON資料時遇到406錯誤
阿新 • • 發佈:2019-02-06
使用的spring是4.3.0版的,解決方法其實很簡單:就是在spring-mvc的配置中少了一句話:<mvc:annotation-driven />
加上這句後就OK了。
下面記錄的是問題出現和解決的過程:
==============================================================================
結合EasyUI時將JSON資料顯示在datagrid中時出現這個錯誤。
用Firebug檢視時問題如下:
顯示出現的錯誤是:406 Not Accepatable ,其中有一句提示:
The resource identified by this request is only capable of generating responses with characteristics
not acceptable according to the request "accept" headers ().
因為easyui的datagrid要求返回的資料是JSON格式的,這句提示說明返回的資料不是JSON格式的。
開始還以為是mybatis中返回的資料有問題,但Controller中直接改為下面的測試方法來返回資料後仍然出現同樣的錯誤。
之前在另一個只有springmvc+easyui沒使用mybatis的專案中進行測試是沒有問題的,這說明與mybatis無關了,還是spring mvc的問題。查找了很久的原因,網上找到一個解決方案:@Controller public class BookController { @RequestMapping("bookList.do") public @ResponseBody ArrayList<Book> getList(){ ArrayList list=new ArrayList(); list.add(new Book(10,"aaa","wa",21.8f,100)); list.add(new Book(11,"bbb","wa",29.0f,200)); list.add(new Book(12,"ccc","www",16.8f,300)); System.out.println(list); return list; } }
<!-- 解決@ResponseBody註解直接返回物件並轉換成JSON時出現406問題,同時解決了返回String型別亂碼的問題 --> <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8</value> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>application/json; charset=UTF-8</value> <value>application/x-www-form-urlencoded; charset=UTF-8</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
這時才發現原來的測試專案的spring-mvc.xml中有一句這樣的配置,而在新的測試專案中少了這一句:
<mvc:annotation-driven />
加上這一句後,新的專案也測試通過了。並且利用mybatis從資料庫中取得的中文資料也可以正常顯示,並不需要前面網上那種解決方案的那一大段配置,網上這種估計適合更低一些版本的。而本人這幾個專案中用的spring是4.3.0 RELEASE版的,高版本的spring據說是不用配置MessageConverter的。
而 <mvc:annotation-driven /> 這句配置如果沒有,個人猜測應該是連@ResponseBody 這樣的註解都不能正常起作用的,因此也可以理解為什麼返回到客戶端的不是JSON格式的資料了。
測試結果:
這裡使用的jackson包分別是:
<!-- json -->
<!-- <dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.3</version>
</dependency>
-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
前面的兩個已經註釋了沒有使用,只使用了jackson-annotation、jackson-core和jackson-databind這3個。