Spring 3.2.* MVC通过Ajax获取JSON数据报406错误

文章来源:http://blog.csdn.net/gbtyy/article/details/17165605

Spring 3.2.x通过@ResponseBody标签返回JSON数据的方法都报406错: Failed to load resource: the server responded with a status of 406 (Not Acceptable) 以及报错描述: The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request “accept” headers () 于是,百度、Google了半天,发现遇到此问题的人挺多的,但是都是说什么添加Jackson什么的,我是采用的fastjson,换成Jackson尝试了半天均还是406。 后来在stackoverflow有人说是Spring 3.2的BUG,于是退回到3.1.*,不再报406了, 虽然换回3.1不报错了,但还是想看看在处理ajax返回json数据的方式上两个版本到底有何区别,debug之。 debug到org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(T returnValue,MethodParameter returnType,ServletServerHttpRequest inputMessage,ServletServerHttpResponse outputMessage),在以下代码处抛出了异常:

[java] view plain copy
if (compatibleMediaTypes.isEmpty()) {
throw new HttpMediaTypeNotAcceptableException(allSupportedMediaTypes);
}
看来是compatibleMediaTypes为空导致。看debug信息,经过比较发现3.1的requestedMediaTypes为[/],而3.2的requestedMediaTypes却为[text/html],producibleMediaTypes都是[application/json],继而发现获取acceptableMediaTypes的方式3.1与3.2不同 3.1的

3.1的

[java] view plain copy 在CODE上查看代码片派生到我的代码片
private List getAcceptableMediaTypes(HttpInputMessage inputMessage) {
try {
List result = inputMessage.getHeaders().getAccept();
return result.isEmpty() ? Collections.singletonList(MediaType.ALL) : result;
} catch (IllegalArgumentException ex) {
if (logger.isDebugEnabled()) {
logger.debug(“Could not parse Accept header: ” + ex.getMessage());
}
return Collections.emptyList();
}
}
3.2的

[java] view plain copy 在CODE上查看代码片派生到我的代码片
private List getAcceptableMediaTypes(HttpServletRequest request) throws HttpMediaTypeNotAcceptableException {
List mediaTypes = this.contentNegotiationManager.resolveMediaTypes(new ServletWebRequest(request));
return mediaTypes.isEmpty() ? Collections.singletonList(MediaType.ALL) : mediaTypes;
}
看来问题就是出在这里了。不知Spring为何改变该实现方式??!!
解决方法如下:

一、第一种 继续用Spring 3.1.4。

二、第二种

[html] view plain copy

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值