中文亂碼是 Java 開發者的「心頭刺」。本文從**編碼本質原理**出發,系統梳理 MyEclipse 多層級編碼設置、項目歷史亂碼根因、批量轉換工具實戰、以及**預防亂碼的工程化規範**,徹底終結亂碼噩夢。
字符 (Char) --[編碼 Encoding]--> 字節 (Byte) --[解碼 Decoding]--> 字符 (Char)
│ │
內存中 Unicode 磁盤/網絡傳輸
│ │
統一碼表 指定編碼表 (GBK/UTF-8/ISO-8859-1)
亂碼 = 編碼時用表 A,解碼時用表 B (A ≠ B)
| 級別 | 路徑 | 作用範圍 | 建議值 |
|---|---|---|---|
| 1. 項目級 | 項目右鍵 → Properties → Resource → Text file encoding | **當前項目所有文件** (覆蓋全局) | UTF-8 | 2. 內容類型級 | Window → Preferences → General → Content Types → 各類型 (Java Class File, JSP, XML, HTML, CSS, JS, Properties...) → Default encoding → Update | **按文件類型**精細控制 (最常被忽略、最關鍵) | UTF-8 |
| 3. 工作區級 | Window → Preferences → General → Workspace → Text file encoding | **新建項目/文件默認** (不影響已存在項目) | UTF-8 |
| 4. 編輯器級 | Window → Preferences → General → Editors → Text Editors → Spelling/Encoding | 編輯器顯示/保存行為 | UTF-8 |
| 5. MyEclipse 級 | Window → Preferences → MyEclipse → Files and Editors → 各文件類型 → Encoding | MyEclipse 專用編輯器 (JSP/HTML/CSS/JS 設計器) | UTF-8 |
| 6. JVM 啟動參數 | MyEclipse.ini 末尾添加 `-Dfile.encoding=UTF-8` | **運行時默認編碼** (影響 `System.getProperty("file.encoding")`、日誌、JSP 編譯) | UTF-8 |
項目初期未統一編碼,**默認 GBK 寫入中文** → 後期全局改 UTF-8 → **GBK 字節流按 UTF-8 解碼** → 亂碼。
# 1. 版本控制提交規範 (.gitattributes)
* text=auto eol=lf
*.java text encoding=utf-8
*.jsp text encoding=utf-8
*.xml text encoding=utf-8
*.properties text encoding=utf-8
# 2. Maven 編碼鎖定 (pom.xml)
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
# 3. Tomcat URI 編碼 (server.xml)
<Connector port="8080" URIEncoding="UTF-8" ... />
# 4. 數據庫連接編碼
jdbc:mysql://localhost:3306/db?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull
# 5. IDE 共享配置
將 .settings/org.eclipse.core.resources.prefs (含 encoding=UTF-8) 提交至版本控制,團隊統一導入。
| 場景 | 現象 | 核心修正點 |
|---|---|---|
| JSP 頁面顯示亂碼 | 頁面頭 `<%@ page pageEncoding="UTF-8" %>` + Tomcat `URIEncoding="UTF-8"` | |
| GET 請求中文參數亂碼 | ISO-8859-1 解碼 | Tomcat 8+ 默認 UTF-8;7 需 `URIEncoding="UTF-8"` 或手動 `new String(param.getBytes("ISO-8859-1"), "UTF-8")` |
| POST 請求中文亂碼 | 請求體解碼錯誤 | Filter `request.setCharacterEncoding("UTF-8")` (必須在讀取參數前) |
| 控制台/日誌輸出亂碼 | Logback/Log4j 編碼 | 配置 ` |
| 數據庫存儲/讀取亂碼 | ??? 或 亂碼 | 表/庫字符集 `utf8mb4`、連接串 `characterEncoding=utf8`、JDBC 驅動版本 ≥ 5.1.13 |
| Properties 文件中文亂碼 | Unicode 轉義 \uXXXX | IDEA 可直接顯示中文;Eclipse 需安裝 Properties Editor 插件或用 `native2ascii` 轉換 |
亂碼本質是**編碼/解碼表不匹配**。解決之道:
將「編碼規範」寫入團隊《開發手冊》,納入 Code Review 清單,**預防遠勝治療**。