亂碼問題是你們在平常開發過程當中常常會遇到的問題,因爲各自環境的不一樣,解決起來也費時費力,本文主要介紹通常性亂碼問題的解決方法與步驟,開發工具採用Eclipse+Tomcat,統一設置項目編碼UTF-8爲例,供你們參考。html
步驟一:首先,檢查JSP頁面聲明的編碼是否正確,正確示例(注意標紅的地方):java
<%@ 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>Insert title here</title> </head> <body> </body> </html>
步驟二:在確認步驟一沒有問題後,接下來檢查項目屬性編碼、 JSP 頁面屬性的編碼和 Java 文件的屬性編碼,項目屬性編碼和文件屬性編碼也須要統一設置爲 UTF-8 ,正確效果以下圖:web
爲了方便起見,能夠對須要統一編碼的文件格式進行編碼關聯設置,以下圖:spring
步驟三:在確認步驟二沒有問題後,接下來就須要檢查 Tomcat 的編碼,須要把 Tomcat 的編碼也設置爲 UTF-8,找到 Tomcat 安裝目錄下的 conf 目錄下的 server.xml 文件,若是沒有修改過 Tomcat 的端口,則直接搜索8080 ,找到對應的 Connector 標籤加上 URIEncoding 屬性,值爲 UTF-8。app
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="UTF-8" />
使用 Eclipse 作爲開發工具,還需修改 Eclipse 中項目對應的 Tomcat 的配置文件,方法同上。工具
至此,經常使用的解決項目中文亂碼的「三碼合一」的配置方法都已經配置好了,爲了完全的解決亂碼問題,咱們還能夠經過在 web.xml 中配置 Spring 的編碼過濾器來處理亂碼問題。開發工具
<!-- 編碼過濾器 --> <filter> <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>