在 Java Web 開發中,HttpServletResponse 直接輸出中文字串時常出現亂碼,根本原因在於瀏覽器與伺服器之間的字元編碼不一致。本文透過三個階段示範問題演進與解決路徑。
response.getWriter().write("您好中國hello");
預設使用 ISO-8859-1 編碼,中文字元無法正確表示,瀏覽器顯示亂碼。
response.setCharacterEncoding("UTF-8");
response.getWriter().write("您好中國hello");
雖然伺服器端以 UTF-8 編碼輸出位元組流,但瀏覽器未收到編碼宣告,仍依預設編碼解析,導致亂碼。
response.setContentType("text/html;charset=UTF-8"); // 關鍵:設定 Content-Type 標頭
response.setCharacterEncoding("UTF-8"); // 設定回應編碼
response.getWriter().write("您好中國hello");
關鍵在於 setContentType("text/html;charset=UTF-8"),它會產生 HTTP 回應標頭:
Content-Type: text/html;charset=UTF-8
告知瀏覽器以 UTF-8 解碼內容。setCharacterEncoding 則決定 getWriter() 回傳的 PrintWriter 內部編碼。兩者結合才能確保端到端編碼一致。
<%@ page contentType="text/html;charset=UTF-8" %>server.xml 的 URIEncoding 屬性setCharacterEncoding 會自動設定 Content-Type 標頭setCharacterEncoding(必須在 getWriter() 前呼叫)request.setCharacterEncoding("UTF-8"))導致參數接收亂碼