首先,response返回有兩種,一種是字節流outputstream,一種是字符流printwrite。
申明:這里為了方便起見,所有輸出都統一用UTF-8編碼。
先說字節流,要輸出“中國",給輸出流的必須是轉換為utf-8的“中國”,還要告訴瀏覽器,用utf8來解析數據
[html] view plain copy
//這句話的意思,是讓瀏覽器用utf8來解析返回的數據
response.setHeader("Content-type", "text/html;charset=UTF-8");
String data = "中國";
OutputStream ps = response.getOutputStream();
//這句話的意思,使得放入流的數據是utf8格式
ps.write(data.getBytes("UTF-8"));
再說字符流,要輸出中國,需要設置response.setCharacterEncoding("UTF-8");
[html] view plain copy
//這句話的意思,是讓瀏覽器用utf8來解析返回的數據
response.setHeader("Content-type", "text/html;charset=UTF-8");
//這句話的意思,是告訴servlet用UTF-8轉碼,而不是用默認的ISO8859
response.setCharacterEncoding("UTF-8");
String data = "中國";
PrintWriter pw = response.getWriter();
pw.write(data);
經驗:1,如果中文返回出現??字符,這表明沒有加response.setCharacterEncoding("UTF-8");這句話。
2,如果返回的中文是“烇湫”這種亂碼,說明瀏覽器的解析問題,應該檢查下是否忘加response.setHeader("Content-type", "text/html;charset=UTF-8");這句話。
如果上面都解決不了,請看更詳細的說明
http://blog.csdn.net/kontrol/article/details/7767983
————————————————
版權聲明:本文為CSDN博主「gavin5033」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/gavin5033/article/details/80408025