首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

Java Web 解決 URL 中文參數亂碼通用方案

     編輯:Java 程式設計入門

中文編碼問題根源分析

URL 傳遞中文參數時,瀏覽器會依據頁面編碼對中文進行編碼(通常為 UTF-8 或 GBK),而伺服器端預設使用 ISO-8859-1 解碼,導致編解碼不一致產生亂碼。傳統 new String(param.getBytes("ISO-8859-1"), "UTF-8") 方式高度依賴部署環境,遷移時極易失效。

通用解決方案:雙端編碼統一

前端編碼(JavaScript)

// 推薦:雙重編碼確保特殊字元安全
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;
    }
}

特殊場景:iframe 與 parent.window.location.href

這兩種跨文檔跳轉方式同樣需要編碼處理:

// 編碼:雙重 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.locationencodeURI(encodeURI())URLDecoder.decode(str, "UTF-8")
表單 POST 提交設定 form accept-charset="UTF-8"request.setCharacterEncoding("UTF-8")

進階建議

  • 全鏈路 UTF-8:頁面、資料庫、JVM、Tomcat 全統一 UTF-8
  • Filter 統一處理:編寫 CharacterEncodingFilter 在進入 Controller 前統一解碼
  • Spring MVC:配置 <mvc:annotation-driven> 自動處理
  • 避免手動 getBytes:依賴容器與標準 API,減少環境依賴
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved