Java 內部運行統一用 UTF-16 (char),但邊界 (輸入/輸出/編譯/存儲) 涉及字節流轉換,若各環節編碼不一致 → 亂碼。
new String(bytes, "ISO-8859-1") → 破壞封裝、到處補丁URIEncoding → 遷移即失效、違背容器與應用分離原則UTF-8 兼容所有語言,無平台綁定,是唯一跨平台穩健選擇。
javac -encoding UTF-8 / Maven <properties><project.build.sourceEncoding>UTF-8</...>
// 必須在讀取任何 request 參數前調用
request.setCharacterEncoding("UTF-8");
web.xml 啟用 Filter (Spring CharacterEncodingFilter / 自定義)
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<meta charset="UTF-8"> (HTML5) 或 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
# MySQL
jdbc:mysql://localhost:3306/db?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
# PostgreSQL
jdbc:postgresql://localhost:5432/db?charSet=UTF-8
# Oracle (驅動 12.1+ 自動 UTF-8,舊版需 orai18n.jar)
jdbc:oracle:thin:@host:1521:sid
# 確保 NLS_LANG=AL32UTF8 (客戶端環境變數)
CHARSET=utf8mb4 (支援 Emoji)new InputStreamReader(is, StandardCharsets.UTF_8)<?xml version="1.0" encoding="UTF-8"?>,解析器自動識別HttpClient / RestTemplate / WebClient 默認 UTF-8,顯式設置 Charset.UTF_8| 框架 | 關鍵配置 |
|---|---|
| Struts 1/2 | web.xml Filter + JSP pageEncoding + struts.xml i18n.encoding=UTF-8 |
| Spring MVC | CharacterEncodingFilter (order=1) + @Controller 默認 UTF-8 |
| Tapestry | 默認 UTF-8,@Inject @Symbol(SymbolConstants.CHARSET) "UTF-8" |
| Hibernate/JPA | 連接 URL encoding + hibernate.connection.charSet=UTF-8 |
| Jdon/EJB | 同 Servlet Filter + 部署描述符 encoding |