zl程序教程

您现在的位置是:首页 >  后端

当前栏目

解决springmvc返回json数据IE出现文件下载和json数据

2023-09-11 14:19:38 时间

 

总结一下使用springmvc时经常会遇到的一个问题。

springmvc返回json数据在IE浏览器中访问,会出现文件下载现象,这是因为IE10以下不支持application/json格式的Response响应,也就是说低于IE10版本一下的IE浏览器都需要使用text/html格式的Response响应;

json数据返回时如果有中文可能会使用浏览器默认编码,如果浏览器编码不支持中文就会出现json返回数据中中文乱码的现象。

解决方法如下:

在maven库中加入下面的包依赖

<!-- Jackson Json处理工具包 -->
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-annotations</artifactId>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
</dependency>

 

在springmvc的配置文件中配置json数据转换器和设置编码格式

 

<!--注解驱动 -->
<mvc:annotation-driven>
    <mvc:message-converters>
        <ref bean="stringHttpMessageConverter"/>
        <ref bean="mappingJackson2HttpMessageConverter"/>
    </mvc:message-converters>
</mvc:annotation-driven>

<bean id="stringHttpMessageConverter"
 class="org.springframework.http.converter.StringHttpMessageConverter"/>

<!--解决IE浏览器json文件下载和json数据中午乱码的问题-->
<bean id="mappingJackson2HttpMessageConverter"
 class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    <property name="supportedMediaTypes">
        <list>
            <value>text/html;charset=UTF-8</value>
            <value>application/json;charset=UTF-8</value>
        </list>
    </property>
</bean>

 

 

 

 

转: https://www.itdaan.com/blog/2017/06/09/24a5cb184fdfe7da7fe388c9836f33a1.html