解决@ResponseBody注解返回中文乱码

解决@ResponseBody注解返回中文乱码

薛定谔的汪 Lv5

  今天在项目中使用@ResponseBody注解,发现返回页面上的中文是乱码,特此记录一下解决方案:

第一种解决方案是用@RequestMapping的produces方法,如下:

1
@RequestMapping(value = "test",produces = "application/json;charset=utf-8")

  在方法上加上这个注解就可以了。但是这样写的话有限制,只能在特定的方法上面使用。如果需要全局都使用的话,需要修改SpringMVC的配置文件。

第二种方式是比较推荐的方式,使用<mvc:message-converters>标签配置,内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!-- 配置注解驱动 -->
<mvc:annotation-driven>
<!-- ResponseBody解决返回字符串汉字乱码 -->
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=utf-8</value>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
  • Title: 解决@ResponseBody注解返回中文乱码
  • Author: 薛定谔的汪
  • Created at : 2017-10-10 18:01:54
  • Updated at : 2023-11-17 19:37:37
  • Link: https://www.zhengyk.cn/2017/10/10/spring/ResponseBody/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments