String 物件採 UTF-16 (Unicode) 儲存。Charset。<form accept-charset="...">)將輸入文字 URLEncode。HttpServletRequest.getParameter() 依預設或指定編碼 URLDecode 為 Unicode 字串。| 環節 | 設定方式 | 建議值 |
|---|---|---|
| JSP 頁面編碼 | <%@ page pageEncoding="UTF-8" %> | UTF-8 |
| 回應輸出編碼 | <%@ page contentType="text/html;charset=UTF-8" %> | UTF-8 |
| 請求解碼 | Filter 設定 request.setCharacterEncoding("UTF-8")(需在讀取參數前) | UTF-8 |
| 資料庫連線 | JDBC URL 附加 characterEncoding=UTF-8(MySQL)或 oracle.jdbc.defaultNChar=true | UTF-8 / UTF-16 |
| HTML Meta | <meta charset="UTF-8"> | UTF-8 |
contentType 不設 pageEncoding → JSP 編譯階段讀取原始檔用預設 ISO-8859-1,中文變亂碼。request.setCharacterEncoding 位置錯誤(在 getParameter 之後) → 無效。GET 請求參數編碼由容器 URIEncoding 決定(Tomcat server.xml <Connector URIEncoding="UTF-8">)。public class EncodingFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
chain.doFilter(req, resp);
}
}
於 web.xml 映射 /* 確保所有請求通過。