編碼不一致:**瀏覽器編碼 → 伺服器解碼 → JVM 內部 Unicode → 伺服器編碼 → 瀏覽器解碼** 任一環節不匹配即產生亂碼。
**最簡單、最常見**。請求體編碼由瀏覽器按頁面編碼發送,伺服器預設 ISO-8859-1 解碼。
request.setCharacterEncoding("UTF-8"); // 必須在 getParameter() 之前
Spring MVC 可用 `CharacterEncodingFilter` 自動攔截所有請求設定編碼。
參數附在 URL,經過 **URL 編碼**(百分號編碼)。伺服器端預設用 ISO-8859-1 解碼 URL。
<Connector port="8080" URIEncoding="UTF-8" ... /> <!-- server.xml -->
所有 GET 請求參數自動以 UTF-8 解碼,包含超連結、重導向、表單 GET。
String raw = request.getParameter("param"); // ISO-8859-1 解碼後的錯誤字串
String correct = new String(raw.getBytes("ISO-8859-1"), "UTF-8");
// 前端
var encoded = encodeURIComponent(chineseParam); // UTF-8 百分號編碼
location.href = "target.jsp?param=" + encoded;
// 後端
String decoded = URLDecoder.decode(request.getParameter("param"), "UTF-8");
本質是發送 Location Header,Header 值需 **URL 編碼**。
String url = "target.jsp?name=" + URLEncoder.encode("中文", "UTF-8");
response.sendRedirect(url);
目標頁接收時同場景二處理(方案 A 最省事)。
`response.getWriter()` 預設 ISO-8859-1,無法表示中文。
// 方式一:同時設定 Content-Type 與字元集 (推薦)
response.setContentType("text/html;charset=UTF-8");
// 方式二:單獨設定字元集 (優先級高於 setContentType)
response.setCharacterEncoding("UTF-8");
JSP 頁面指令 `<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>` 已自動處理。
**只要全鏈路編碼一致,亂碼零發生。**