Spring WebMVC 4.1返回json时导致的 406(Not Acceptable)问题

来源:互联网 发布:java ee是什么 编辑:程序博客网 时间:2024/06/06 02:48

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.具体实现
  @RequestMapping("/listAll")  @ResponseBody  public Map<String, Object> listAll() {    List<Device> list = deviceService.listAll();    if (list != null) {      Map<String, Object> result = new HashMap<String, Object>();      result.put("total", list.size());      result.put("rows", list);      return result;    }    return null;  }

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使用了网上所说的:

<dependency><groupId>org.codehaus.jackson</groupId><artifactId>jackson-mapper-asl</artifactId><version>1.9.10</version></dependency>

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

import org.codehaus.jackson.JsonEncoding;import org.codehaus.jackson.JsonGenerator;import org.codehaus.jackson.map.ObjectMapper;import org.codehaus.jackson.map.SerializationConfig;

而4.1.0开始,使用了:

<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.5.1</version></dependency>
spring-webmvc-4.1.0.RELEASE-sources\org\springframework\web\servlet\view\json\AbstractJackson2View.java

import com.fasterxml.jackson.annotation.JsonView;import com.fasterxml.jackson.core.JsonEncoding;import com.fasterxml.jackson.core.JsonGenerator;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.SerializationFeature;

6.解决问题

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

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

Spring MVC 4.1.4 RESTFUL风格返回JSON数据406错误处理

为什么不让我早点看到。。。

3 1
原创粉丝点击