解决springmvc使用ResponseBody注解返回json中文乱码问题

spring版本:4.2.5.RELEASE

查看“org.springframework.http.converter.StringHttpMessageConverter”源码,中有一段说明:

By default, this converter supports all media types ({@code */*}),
and writes with a {@code Content-Type} of {@code text/plain}. This can be overridden
by setting the {@link #setSupportedMediaTypes supportedMediaTypes} property.

media type :(also MIME type and content type) is a two-part identifier for file formats and format contents transmitted on the Internet.
所以可以制定文件格式和编码,
“text/html;charset=UTF-8”:解决浏览器直接访问接口时中文乱码问题。
“application/json;charset=UTF-8”:解决ajax【dataType:"json"】时中文乱码问题。

在springmvc的配置文件中加入如下配置:

    <!-- 让DispatchServlet启动基于annotation的HandlerMapping -->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <!-- 解决Controller返回json中文乱码问题 -->
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <!-- <property name="supportedMediaTypes" value="text/html;charset=UTF-8" /> -->
                <!-- <property name="supportedMediaTypes" value="application/json;charset=UTF-8" > -->
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

==================== 分割线  ====================

其他还有各种中文乱码问题:

1、jsp:声明页面编码方式

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登录</title>
</head>
<body>
……
</body>
</html>

2、过滤器:在web.xml中加入如下代码

  <!-- 中文编码过滤器 -->
  <filter>
      <filter-name>encoding</filter-name>
      <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
      <init-param>
          <param-name>encoding</param-name>
          <param-value>UTF8</param-value>
      </init-param>
  </filter>
  <filter-mapping>
      <filter-name>encoding</filter-name>
      <url-pattern>/</url-pattern>
  </filter-mapping>

3、修改tomcat的server.xml

<Connector URIEncoding="UTF-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>

总结:搞清楚出现乱码的原因以及每一个配置的作用是解决出现乱码的关键。

QQ技术交流群:282575808

--------------------------------------

声明: 原创文章,未经允许,禁止转载!

--------------------------------------

原文地址:https://www.cnblogs.com/xxoome/p/6829708.html