萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

AJAX 傳中文到 Servlet 產生亂碼的解決方案(GET/POST 分別處理)

現象

前端 AJAX 傳遞中文參數到 Servlet,`request.getParameter()` 取得的值出現亂碼。原因在於 Tomcat 預設以 ISO-8859-1 解碼 URL,而瀏覽器實際編碼可能為 UTF-8 或 GBK。

Servlet 統一設定回應編碼

response.setContentType("text/html;charset=UTF-8");

GET 請求處理

// 前端
var url = "/emp/FindSpecial?selcol=" + encodeURIComponent("軟件工程");
xmlHttp.open("GET", url, true);

// 後端:ISO-8859-1 → GBK/GB2312(UTF-8 不行)
String selcol = new String(request.getParameter("selcol").getBytes("ISO-8859-1"), "GBK");

POST 請求處理

// 前端
xmlHttp.open("POST", "/emp/FindSpecial", true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send("selcol=" + encodeURIComponent("軟件工程"));

// 後端:ISO-8859-1 → UTF-8(GBK/GB2312 不行)
String selcol = new String(request.getParameter("selcol").getBytes("ISO-8859-1"), "UTF-8");

原理說明

  • response.setContentType 只影響輸出編碼。
  • 輸入參數經由 Tomcat 以 ISO-8859-1 解碼位元組,需手動轉回原始編碼。
  • GET 請求參數在 URL 中,瀏覽器常以 UTF-8 編碼但 Tomcat 按 ISO-8859-1 解碼 → 轉 GBK 可還原;POST 請求參數在 Body,若前端已 `encodeURIComponent`(UTF-8),則轉 UTF-8 正確。

最佳實務建議

  1. 全站統一使用 UTF-8:頁面 ``、JS `encodeURIComponent`、Servlet `request.setCharacterEncoding("UTF-8")`(需在 `getParameter` 前呼叫)、DB 連線 `characterEncoding=utf8`。
  2. Tomcat 8+ 可在 `server.xml` `` 加入 `URIEncoding="UTF-8"` 徹底解決 GET 亂碼。
copyright © 萬盛學電腦網 all rights reserved