在 Spring MVC 中解決中文亂碼問題,需要從 請求參數編碼 和 響應內容編碼 兩方面入手。以下是完整的解決方案:
一、解決請求參數中文亂碼
1. POST 請求編碼(表單提交)
配置 CharacterEncodingFilter
在 web.xml
中添加 Spring 提供的字符編碼過濾器,強制請求和響應使用 UTF-8 編碼:
<!-- 解決 POST 請求中文亂碼 -->
<filter><filter-name>encodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param>
</filter>
<filter-mapping><filter-name>encodingFilter</filter-name><url-pattern>/*</url-pattern>
</filter-mapping>
2. GET 請求編碼(URL 參數)
修改 Tomcat 的 server.xml
在 Tomcat 的 conf/server.xml
文件中,找到 Connector 配置,添加 URIEncoding="UTF-8"
:
<Connector port="8080" protocol="HTTP/1.1"URIEncoding="UTF-8" <!-- 關鍵配置 -->connectionTimeout="20000"redirectPort="8443" />
二、解決響應內容中文亂碼
1. 配置消息轉換器(JSON 響應)
在 Spring MVC 配置文件中(如 spring-mvc.xml
),設置 MappingJackson2HttpMessageConverter
的默認編碼:
<mvc:annotation-driven><mvc:message-converters><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><bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"><property name="supportedMediaTypes"><list><value>application/json;charset=UTF-8</value></list></property></bean></mvc:message-converters>
</mvc:annotation-driven>
2. 全局響應編碼配置
在 web.xml
中添加響應編碼過濾器:
<filter><filter-name>responseFilter</filter-name><filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
</filter>
<filter-mapping><filter-name>responseFilter</filter-name><url-pattern>/*</url-pattern>
</filter-mapping>
三、其他注意事項
1. JSP 頁面編碼設置
確保 JSP 頁面頭部聲明了 UTF-8 編碼:
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
2. 數據庫連接編碼
如果涉及數據庫操作,在 JDBC URL 中指定字符集:
jdbc.url=jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=UTF-8
3. Ajax 請求編碼
對于前端 Ajax 請求(如 jQuery),顯式設置 contentType
:
$.ajax({url: '/api/data',type: 'POST',contentType: 'application/x-www-form-urlencoded; charset=UTF-8', // 明確設置編碼data: { name: '張三' },success: function(response) {console.log(response);}
});
四、驗證配置是否生效
-
POST 請求測試
提交表單后,觀察后端是否能正確接收中文參數。 -
GET 請求測試
訪問帶中文參數的 URL,如http://localhost:8080/user?name=張三
,檢查是否亂碼。 -
響應內容測試
返回 JSON 數據或視圖頁面,確認中文字符正常顯示。
五、常見問題排查
-
亂碼僅在部分場景出現
- 檢查是否遺漏了
GET
請求的 Tomcat 配置。 - 確認前端請求頭
Content-Type
是否攜帶charset=UTF-8
。
- 檢查是否遺漏了
-
Spring Boot 項目配置
在application.properties
中添加:server.servlet.encoding.force=true server.servlet.encoding.charset=UTF-8
-
Tomcat 9+ 的兼容性
新版 Tomcat 默認使用 UTF-8 編碼,但仍需確保URIEncoding
配置正確。
通過以上步驟,可以徹底解決 Spring MVC 中的中文亂碼問題!