在 Struts2 應用中,前端透過 JSON 向後端傳遞中文參數時,常因編碼不一致導致亂碼。本文提供雙端編碼/解碼的標準解決方案。
在 JavaScript 中使用 encodeURI 進行兩次編碼,確保特殊字符正確傳輸:
var url = "orderPrint.action?roomName=" + encodeURI(encodeURI(roomName));
$.post(url, function(data) {
// 回調處理
});
在 Action 或 Service 層使用 URLDecoder.decode 以 UTF-8 還原:
String room = URLDecoder.decode(orderBean.getRoomName(), "UTF-8");
此方案適用於 Struts2 以 GET/POST 方式接收 URL 參數、AJAX 傳遞中文、REST 風格 API 參數傳遞等場景。
Content-Type: application/json;charset=UTF-8 即可server.xml 的 Connector 配置 URIEncoding="UTF-8"