先看一个Controller方法
@ResponseBody
@RequestMapping(value = "/getUserById/{id}",method = {RequestMethod.GET})
public User getUserById(@PathVariable int id, HttpServletRequest request, HttpServletResponse response, Model model){
response.setContentType("text/html;charset=UTF-8");
response.setHeader("content-disposition", "inline;filename=*.txt");
User user = userService.getUserById(id);
return user;
}
返回一个User实体,通过@ResponseBody注解格式化为json对象输出的页面
但是在IE浏览器下面,会出现下载json文件的提示,而不是在页面显示
解决方法1:
在controller方法中加上这个就不会出现下载,而是显示json
response.setContentType("text/html;charset=UTF-8");
response.setHeader("content-disposition", "inline;filename=*.txt");
效果如下图:
解决方法2:在spring-mvc.xml中配置
<mvc:annotation-driven>
<mvc:message-converters register-defaults="false">
<!-- 解决AJAX中文乱码 -->
<beans:bean class="org.springframework.http.converter.StringHttpMessageConverter">
<beans:constructor-arg value="UTF-8"/>
</beans:bean>
<beans:bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<beans:property name="prettyPrint" value="false" />
<beans:property name="supportedMediaTypes">
<beans:list>
<beans:value>text/html;charset=UTF-8</beans:value>
<beans:value>application/json</beans:value>
</beans:list>
</beans:property>
<beans:property name="objectMapper">
<beans:bean class="com.fasterxml.jackson.databind.ObjectMapper">
<beans:property name="serializationInclusion">
<beans:value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</beans:value>
</beans:property>
</beans:bean>
</beans:property>
</beans:bean>
</mvc:message-converters>
</mvc:annotation-driven>
效果如下图:
上述配置,需要依赖jar包,如果工程使用的是maven在pom.xml中加入以下依赖:
pom文件中需要下面的jar包
<!-- json数据 -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.7</version>
</dependency>
<!-- Jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${version.jackson}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${version.jackson}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jaxb-annotations</artifactId>
<version>${version.jackson}</version>
</dependency>