URL 傳遞中文參數時,瀏覽器會依據頁面編碼對中文進行編碼(通常為 UTF-8 或 GBK),而伺服器端預設使用 ISO-8859-1 解碼,導致編解碼不一致產生亂碼。傳統 new String(param.getBytes("ISO-8859-1"), "UTF-8") 方式高度依賴部署環境,遷移時極易失效。
// 推薦:雙重編碼確保特殊字元安全
var title = "中文標題";
title = encodeURIComponent(title); // 先 UTF-8 編碼
// title = escape(encodeURIComponent(title)); // 舊版相容寫法
var url = "${pageContext.request.contextPath}/print/printList!printTable.action?title=" + title;
window.location.href = url;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
public String getDecodedParam(HttpServletRequest request, String paramName) {
try {
String encodedValue = request.getParameter(paramName);
if (encodedValue == null) return null;
// 統一使用 UTF-8 解碼
return URLDecoder.decode(encodedValue, "UTF-8");
} catch (Exception e) {
// 記錄日誌,返回原值或拋出異常
return encodedValue;
}
}
這兩種跨文檔跳轉方式同樣需要編碼處理:
// 編碼:雙重 encodeURI 確保完整性
var encodedStr = encodeURI(encodeURI("包含中文的字串"));
// 使用場景
parent.window.location.href = "target.jsp?param=" + encodedStr;
// 或
document.getElementById("myIframe").src = "target.jsp?param=" + encodedStr;
// 後端解碼同前
String decoded = URLDecoder.decode(request.getParameter("param"), "UTF-8");
| 場景 | 前端編碼 | 後端解碼 |
|---|---|---|
| 一般 URL 參數 | encodeURIComponent() | URLDecoder.decode(str, "UTF-8") |
| iframe src / parent.location | encodeURI(encodeURI()) | URLDecoder.decode(str, "UTF-8") |
| 表單 POST 提交 | 設定 form accept-charset="UTF-8" | request.setCharacterEncoding("UTF-8") |
<mvc:annotation-driven> 自動處理