GET 請求 URL 參數包含中文時,Tomcat 預設用 ISO-8859-1 解碼,導致中文亂碼。IE 瀏覽器更嚴重,甚至編碼不一致。
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
URIEncoding="UTF-8" />
關鍵屬性:URIEncoding="UTF-8" 強制 Tomcat 以 UTF-8 解碼 URL 參數。
即使伺服器設定正確,IE 等舊瀏覽器仍可能發送錯誤編碼。前端主動編碼最保險:
// jQuery load 範例
var url = 'targetPage.jsp?param=' + encodeURIComponent('中文參數');
$('#divID').load(url);
// 一般 AJAX
$.ajax({
url: 'api/search',
data: { keyword: '中文關鍵字' }, // jQuery 內建會 encodeURIComponent
// 或手動組 URL 時
url: 'api/search?keyword=' + encodeURIComponent('中文關鍵字')
});
| 函式 | 編碼範圍 | 適用場景 |
|---|---|---|
escape() | 非 ASCII、非字母數字、非 * @ - _ + . / | 已棄用,勿用 |
encodeURI() | 非 ASCII、非保留字元 (; , / ? : @ & = + $ #) | 編碼完整 URL |
encodeURIComponent() | 非 ASCII、非字母數字、非 - _ . ! ~ * ' ( ) | 編碼單一參數值 (最常用) |
server.xml 設定 URIEncoding="UTF-8"encodeURIComponent()<%@ page contentType="text/html;charset=UTF-8" %>characterEncoding=utf8 (MySQL) / NLS_LANG (Oracle)前後端統一 UTF-8,徹底根治中文亂碼。