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

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 ()后来在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),在以下代码处抛出了异常:

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的

private List<MediaType> getAcceptableMediaTypes(HttpInputMessage inputMessage) { try { List<MediaType> 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的private List<MediaType> getAcceptableMediaTypes(HttpServletRequest request) throws HttpMediaTypeNotAcceptableException { List<MediaType> mediaTypes = this.contentNegotiationManager.resolveMediaTypes(new ServletWebRequest(request)); return mediaTypes.isEmpty() ? Collections.singletonList(MediaType.ALL) : mediaTypes; }看来问题就是出在这里了。不知Spring为何改变该实现方式??!!

解决方法如下:

一、第一种继续用Spring 3.1.4。

二、第二种

<?xml version="1.0" encoding="UTF-8"?><beans xmlns=""xmlns:xsi="" xmlns:context=""xmlns:aop="" xmlns:tx=""xmlns:mvc=""xsi:schemaLocation="">

把spring-mvc-3.0.xsd 升级到spring-mvc-3.2.xsd

<?xml version="1.0" encoding="UTF-8"?><beans xmlns=""xmlns:xsi="" xmlns:context=""xmlns:aop="" xmlns:tx=""xmlns:mvc=""xsi:schemaLocation="">然后把<mvc:annotation-driven>修改成如下格式<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" /> <bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean"> <property name="favorPathExtension" value="false" /><property name="favorParameter" value="false" /> <property name="ignoreAcceptHeader" value="false" /> <property name="mediaTypes" > <value>atom=application/atom+xmlhtml=text/htmljson=application/json*=*/*</value> </property></bean>三、第三种

详情见下面的地址点击打开链接

四、第四种

spring 3.2时requestedMediaTypes却为[text/html]的情况报406错误,还有一个原因可能是由于采用的后缀有关,如果使用*.htm,*.html等,默认就会采用[text/html]编码,若改成*.json,*.shtml等就OK

当明知不可挽回,唯一补偿的方法就是怀念,

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

相关文章:

你感兴趣的文章:

标签云: