計算機底層只識別位元組。亂碼發生於:**發送端編碼 ≠ 接收端解碼**。統一全鏈路 UTF-8 是唯一正解。
POST /handle.jsp HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 49
username=%E4%B8%96%E7%95%8C%E6%9D%AF&password=123
<!-- %E4%B8%96%E7%95%8C%E6%9D%AF = "世界杯" 的 UTF-8 URL 編碼 -->
@WebFilter("/*")
public class EncodingFilter implements Filter {
private String encoding = "UTF-8";
private boolean forceEncoding = true;
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
if (forceEncoding || request.getCharacterEncoding() == null) {
request.setCharacterEncoding(encoding);
}
if (forceEncoding) {
response.setCharacterEncoding(encoding);
}
chain.doFilter(request, response);
}
}
配置在 `web.xml` 首位,覆蓋所有請求,**一次配置,全局生效**。
URL 中參數經過瀏覽器 URL 編碼 (通常 UTF-8),但 Tomcat **默認用 ISO-8859-1 解碼 Query String**。
| 方案 | 配置 | 優點 | 缺點 |
|---|---|---|---|
| Tomcat 全局 | server.xml: `URIEncoding="UTF-8"` | 零代碼侵入,覆蓋所有 GET | 需修改服務器配置,遷移需同步 |
| 手動轉碼 | `new String(req.getParameter("k").getBytes("ISO-8859-1"), "UTF-8")` | 無需改配置 | 極易遺漏,性能差,不推薦 |
| Spring MVC | `@RequestParam` 自動處理 (配合 Filter) | 框架層透明化 | 依賴 Spring |
**統一修改 `server.xml` Connector 設置 `URIEncoding="UTF-8"`**,並配合 Filter 強制 POST 編碼,徹底消除參數亂碼。
<!-- 子窗口 popup.jsp -->
<script>
// 獲取父窗口輸入框值
var parentVal = window.opener.document.getElementById('parentInput').value;
// 或 jQuery
var val = $(window.opener.document).find('#parentInput').val();
// 寫回父窗口
window.opener.document.getElementById('result').value = '選擇結果';
window.opener.doCallback('selected'); // 調用父頁面函數
window.close();
</script>
// 發送端 (JS)
fetch('/api/save', {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
body: new URLSearchParams({name: '中文'}) // 自動 UTF-8 編碼
});
// 接收端 (Servlet/Controller)
request.setCharacterEncoding("UTF-8"); // Filter 已處理可省略
String name = request.getParameter("name"); // 正確
<form method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="text" name="description"/>
</form>
✅ 所有 .jsp/.java/.js/.css 文件保存為 UTF-8 (無 BOM)
✅ JSP 頁面: pageEncoding="UTF-8" contentType="text/html;charset=UTF-8"
✅ HTML: <meta charset="UTF-8">
✅ Tomcat server.xml: URIEncoding="UTF-8" useBodyEncodingForURI="true"
✅ web.xml: CharacterEncodingFilter (forceEncoding=true) 映射 /*
✅ JDBC URL: useUnicode=true&characterEncoding=utf8mb4
✅ 數據庫/表/列: CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
✅ JS URL 參數: encodeURIComponent() / decodeURIComponent()
✅ 下載文件名: RFC 5987 filename* 編碼
✅ 日志/控制台輸出: logback encoding=UTF-8