JSP 頁面透過 JavaScript (AJAX/location.href) 傳遞中文參數,後端接收出現亂碼。
// 關鍵:encodeURIComponent 執行兩次
var encoded = encodeURIComponent(encodeURIComponent(chineseStr));
// 例:"測試" → "%E6%B5%8B%E8%AF%95" → "%25E6%25B5%258B%25E8%25AF%2595"
var url = '/api/user?name=' + encoded;
// 或表單提交
form.action = '/submit?keyword=' + encoded;
為什麼雙重? 某些框架/伺服器會自動解碼一次,雙重編碼確保經過兩次解碼後仍為原始 UTF-8 位元組序列。
<%@ page pageEncoding="UTF-8" %>
<%@ page import="java.net.URLDecoder" %>
<%
String encoded = request.getParameter("name");
String decoded = null;
if (encoded != null) {
try {
// 對應雙重編碼,解碼兩次
decoded = URLDecoder.decode(URLDecoder.decode(encoded, "UTF-8"), "UTF-8");
// 或單次 (視實際情況)
// decoded = URLDecoder.decode(encoded, "UTF-8");
} catch (Exception e) {
decoded = "解碼失敗";
}
}
%>
修改 conf/server.xml:
<Connector port="8080" protocol="HTTP/1.1"
URIEncoding="UTF-8"
useBodyEncodingForURI="true" />
配合 Filter:
@WebFilter("/*")
public class EncodingFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
req.setCharacterEncoding("UTF-8");
res.setCharacterEncoding("UTF-8");
chain.doFilter(req, res);
}
}
**配置後**:前端只需單次 encodeURIComponent,後端直接 request.getParameter() 即得正確中文,**完全不需手動解碼**。
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title>發送測試</title></head>
<body>
<input id="input" value="測試中文參數">
<button onclick="sendGet()">GET 請求</button>
<button onclick="sendPost()">POST AJAX</button>
<div id="result"></div>
<script>
function sendGet() {
var val = document.getElementById('input').value;
// 單次編碼 (配合 Tomcat UTF-8 即可)
var encoded = encodeURIComponent(val);
fetch('/receiver.jsp?name=' + encoded)
.then(r => r.text())
.then(html => document.getElementById('result').innerHTML = html);
}
function sendPost() {
var val = document.getElementById('input').value;
fetch('/receiver.jsp', {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
body: 'name=' + encodeURIComponent(val)
}).then(r => r.text())
.then(html => document.getElementById('result').innerHTML = html);
}
</script>
</body></html>
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<%
// Tomcat 已配 URIEncoding=UTF-8 時,直接可用
String name = request.getParameter("name");
// 兼容未配置環境:手動解碼
// String name = new String(request.getParameter("name").getBytes("ISO-8859-1"), "UTF-8");
%>
<h3>接收到: <%=name%></h3>
<p>Method: <%=request.getMethod()%></p>
<p>QueryString: <%=request.getQueryString()%></p>
application/x-www-form-urlencoded:需 request.setCharacterEncoding("UTF-8") (Filter 統一處理)multipart/form-data:檔案上傳,參數解碼由 multipart 解析器決定 (Commons FileUpload 需設定 encoding)application/json:標準 UTF-8,Spring MVC @RequestBody 自動處理| 環境 | 前端編碼 | 後端處理 | 備註 |
|---|---|---|---|
| Tomcat 配置 UTF-8 + Filter | encodeURIComponent(str) (單次) | request.getParameter() 直接用 | ✅ 推薦、最簡單 |
| 無法修改 Tomcat 配置 | encodeURIComponent(encodeURIComponent(str)) (雙重) | URLDecoder.decode(URLDecoder.decode(p, "UTF-8"), "UTF-8") | 兼容舊系統 |
| 舊專案 GBK 編碼 | encodeURIComponent(str) (頁面 GBK) | new String(p.getBytes("ISO-8859-1"), "GBK") | 不建議新專案用 |
**核心原則:全棧統一 UTF-8**。配置 Tomcat URIEncoding="UTF-8" + CharacterEncodingFilter 後,前端單次 encodeURIComponent,後端零代碼直接取參數。若無法修改伺服器配置,採用「前端雙重編碼、後端雙重解碼」兼容方案。拒絕手動 getBytes("ISO-8859-1") 硬碼,改用標準 URLDecoder 或伺服器層面統一解決。