Eclipse 項目編碼 UTF-8,瀏覽器編碼 GBK,PrintWriter 直接輸出中文顯示亂碼。
response.getWriter() 返回的 PrintWriter 使用 response.getCharacterEncoding()(默認 ISO-8859-1)編碼。若未設置 response.setCharacterEncoding("GBK"),則按 ISO-8859-1 寫入字節流,瀏覽器按 GBK 解碼導致亂碼。
response.setCharacterEncoding("GBK"); // 必須在 getWriter() 之前
response.setContentType("text/html;charset=GBK");
PrintWriter out = response.getWriter();
out.write("中文內容");
PrintWriter out = new PrintWriter(
new OutputStreamWriter(response.getOutputStream(), "GBK"), true);
out.write("中文內容");
response.getWriter() 的默認編碼邏輯。URIEncoding)。<meta charset="UTF-8">。