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

Spring 4.1.x JSON返回导致的406错误解决方案
在Tomcat 7和Spring 4.1.4环境下,返回JSON数据时遇到406 Not Acceptable错误。通过排查发现可能与Spring版本有关。降低版本至4.0.9后问题解决。进一步分析4.0.9和4.1.0的源码,发现在JSON处理上有差异。最终,通过引入fasterxml库并在4.1.4版本下修复了问题。

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错误处理

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

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值