瀏覽器 → Web 服務器 → 應用代碼 → 數據庫,任一節點編碼不匹配即產生亂碼。統一建議:全鏈路 UTF-8,國際化首選,避免 GBK/GB2312 兼容性陷阱。
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><%@ page contentType="text/html; charset=UTF-8" %>| 容器 | 配置項 | 示例 |
|---|---|---|
| Tomcat (server.xml Connector) | URIEncoding + useBodyEncodingForURI | <Connector port="8080" URIEncoding="UTF-8" useBodyEncodingForURI="true" /> |
| Jetty / SAP WAS | 通常自動轉碼,無需額外配置 | - |
最佳實踐: URL 參數避免中文,採用字典映射或 POST 表單傳遞。
// 請求編碼 (必須在讀取參數前調用)
request.setCharacterEncoding("UTF-8");
// 響應編碼
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
推薦配置 CharacterEncodingFilter (Spring CharacterEncodingFilter / 手寫 Filter) 映射 /*,強制全局請求/響應 UTF-8,徹底解決表單提交亂碼。
jdbc:mysql://host:3306/db?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNullutf8mb4, Oracle: AL32UTF8)。VARCHAR/CHAR:改為 BINARY 屬性或 ALTER TABLE ... CONVERT TO CHARACTER SET utf8mb4。TEXT/BLOB:需應用層轉碼工具類。public class EncodingUtil {
public static String isoToUtf8(String iso) {
if (iso == null || iso.isEmpty()) return "";
try {
return new String(iso.getBytes("ISO-8859-1"), "UTF-8");
} catch (Exception e) {
throw new RuntimeException("編碼轉換失敗", e);
}
}
}
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">header("Content-Type: text/html; charset=UTF-8");$conn = mysqli_connect(host, user, pass, db);
mysqli_set_charset($conn, "utf8"); // 或 mysqli_query($conn, "SET NAMES 'utf8'");
PDO 方式:new PDO("mysql:host=...;dbname=...;charset=utf8", user, pass);
IDE/編輯器保存為 UTF-8 (無 BOM),避免 BOM 導致 header() 失效或輸出異常。
| 場景 | 現象 | 根因 | 修復 |
|---|---|---|---|
| URL 參數中文 | 亂碼 | Tomcat 默認 ISO-8859-1 解碼 URL | Connector 加 URIEncoding="UTF-8" 或改 POST/字典映射 |
| JSP 直接輸出中文 | 亂碼 | 頁面指令/Response 編碼缺失 | 補 pageEncoding + response.setCharacterEncoding |
| 表單 POST 中文 | 亂碼 | 請求體編碼未設 (瀏覽器發 UTF-8,服務器按 ISO 讀) | Filter/代碼 request.setCharacterEncoding("UTF-8") |
| 數據庫讀寫中文 | 亂碼/問號 | 連接字符集不匹配 / 表字符集非 UTF-8 | JDBC URL characterEncoding=UTF-8 + 表轉 utf8mb4 |
| MySQL TEXT 類型 | 亂碼 | 舊版本字符集處理缺陷 | 轉碼工具類 / 升級 MySQL + 轉表字符集 |
utf8mb4 支援 Emoji)。遵循三大鐵律,亂碼問題將成為歷史。