Spring WebMVC 4.1返回json时 406(Not Acceptable)

时间:2023-03-08 18:22:55

1.问题现象Tomcat7+Spring4.1.4,返回json字符串时发生406错误

The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers.

HTTP Status 406 -


type Status report

message

description The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers.


Apache Tomcat/7.0.52

2.具体实现

  1. @RequestMapping("/listAll")
  2. @ResponseBody
  3. public Map<String, Object> listAll() {
  4. List<Device> list = deviceService.listAll();
  5. if (list != null) {
  6. Map<String, Object> result = new HashMap<String, Object>();
  7. result.put("total", list.size());
  8. result.put("rows", list);
  9. return result;
  10. }
  11. return null;
  12. }

3.网上调查

按照问题现象在网上搜了一下类似问题不少,代表性的有以下几篇:

The resource identified by this request is only capable of generating responses with characteristics

Spring MVC + JSON = 406 Not Acceptable

Spring 3 MVC And JSON Example

前两篇无法解决问题,将第三篇的例子下载下来,运行,成功返回json数据

4.定位

因为例子中用了spring3.2,所以怀疑是spring版本问题。对Spring版本进行替换测试,降到4.0.9时,成功返回json字符串。

5.查找根源

下载4.0.9和4.1.0的spring-webmvc源代码进行对比。

看到在json处理时稍有不同。

4.0.9使用了网上所说的:

  1. <dependency>
  2. <groupId>org.codehaus.jackson</groupId>
  3. <artifactId>jackson-mapper-asl</artifactId>
  4. <version>1.9.10</version>
  5. </dependency>

\spring-webmvc-4.0.9.RELEASE-sources\org\springframework\web\servlet\view\json\MappingJacksonJsonView.Java

  1. import org.codehaus.jackson.JsonEncoding;
  2. import org.codehaus.jackson.JsonGenerator;
  3. import org.codehaus.jackson.map.ObjectMapper;
  4. import org.codehaus.jackson.map.SerializationConfig;

而4.1.0开始,使用了:

  1. <dependency>
  2. <groupId>com.fasterxml.jackson.core</groupId>
  3. <artifactId>jackson-databind</artifactId>
  4. <version>2.5.1</version>
  5. </dependency>

spring-webmvc-4.1.0.RELEASE-sources\org\springframework\web\servlet\view\json\AbstractJackson2View.java

  1. import com.fasterxml.jackson.annotation.JsonView;
  2. import com.fasterxml.jackson.core.JsonEncoding;
  3. import com.fasterxml.jackson.core.JsonGenerator;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import com.fasterxml.jackson.databind.SerializationFeature;

6.解决问题

引入fasterxml的jar包,改回spring4.1.4,问题解决。

7.后记:就在要发表文章的时候,在下方预览中看到一篇

今天在使用spring4.1.4,使用ResponseBody注解返回JSON格式的数据的时候遇到406错误。

解决办法,导入jackson2.X的jar包:

jackson-annotations-2.4.4.jar、jackson-core-2.4.4.jar、jackson-databind-2.4.4.jar。

spring mvc4.1.4使用了jackson2来处理JSON,jackson2的jar包为以上三个,导入之后问题解决。