使用spring mvc返回JSON,chrome可以,firefox不行的问题定位
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用spring mvc返回JSON,chrome可以,firefox不行的问题定位相关的知识,希望对你有一定的参考价值。







<bean
>
<property name="defaultContentType" value="application/json"/>
<property name="mediaTypes">
<map>
<entry key="html" value="text/html;charset=UTF-8"/>
<entry key="json" value="application/json;charset=UTF-8"/>
<entry key="xml" value="application/xml;charset=UTF-8"/>
</map>
</property>
<property name="viewResolvers">
<list>
<bean
>
<property name="cache" value="false"/>
<property name="prefix" value=""/>
<property name="suffix" value=".ftl"/>
<property name="exposeSpringMacroHelpers" value="true"/>
<property name="exposeRequestAttributes" value="true"/>
<property name="exposeSessionAttributes" value="true"/>
<property name="allowSessionOverride" value="true"/>
<property name="contentType" value="text/html;charset=UTF-8"/>
</bean>
</list>
</property>
<property name="defaultViews">
<list>
<bean
>
<property name="objectMapper" ref="objectMapper"/>
<property name="contentType" value="application/json;charset=UTF-8"/>
<property name="modelKeys">
<set>
<value>msg</value>
<value>res</value>
<value>errmsg</value>
</set>
</property>
</bean>
<bean id="marshallingView"
>
<property name="marshaller" ref="xstreamMarshaller"></property>
<property name="modelKey" value="msg"></property>
<property name="contentType" value="application/xml"/>
</bean>
</list>
</property>
</bean>






2、获得转换器中支持Accept的media类型:*/*
3、转换器中支持的media类型是否兼容请求过来的Accept类型:*/*
4、根据请求等参数选择最佳的view
配置文件件配置了defaltView为MappingJackson2JsonView和MarshallingView,顺序匹配,为*时直接匹配上第一种,直播选择MappingJackson2JsonView解析。

2、获得转换器中支持Accept的media类型:*/*
3、转换器中支持的media类型是否兼容请求过来的Accept类型:text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8
4、根据请求等参数选择最佳的view
配置文件件配置了defaltView为MappingJackson2JsonView和MarshallingView,顺序匹配,当匹配到application/xml时,直播返回使用MarshallingView解析。
以上步骤均是controller中没有加headers = { "Accept=application/json" }的情况,那为什么加了这段代码,firefox就可以运行了呢?
这时对应上面的步骤结果为:
2、获得转换器中支持Accept的media类型:application/json;q=0.8
3、转换器中支持的media类型是否兼容请求过来的Accept类型:application/json;q=0.8
4、根据请求等参数选择最佳的view:candidateViews类型为application/json,自然用MappingJackson2JsonView解析。
看上面的步骤大家已经明白了,加上Accept=application/json后获取的media类型就可以直接为application/json了,所以可以直接使用MappingJackson2JsonView解析,进而返回json数据格式。
再做了个实验,就是调换了一下defaultVeiws的配置顺序,把MarshallingView放在前面,在不加Accept=application/json,用chrome请求时,结果返回xml格式。
也就是说当accept是*/*时,他是顺序匹配的。
在spring mvc中,如果想返回的格式是指定的,也可以配置produces变量:
@RequestMapping(value = "/upload",produces="application/json;charset=UTF-8")
也可以达到同样的效果。
结论:
使用spring mvc时,如果返回的数据格式不正确,需要看一下请求头部的accept、controller层的header配置、以及配置文件中模板的渲染类型和配置顺序,通过这三个方式可以定位出原因。
以上是关于使用spring mvc返回JSON,chrome可以,firefox不行的问题定位的主要内容,如果未能解决你的问题,请参考以下文章