解決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

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

聲明: 原創文章,未經允許,禁止轉載!

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM