http://blog.csdn.net/simon_1/article/details/9092747
首先,response返回有兩種,一種是字節流outputstream,一種是字符流printwrite。
申明:這里為了方便起見,所有輸出都統一用UTF-8編碼。
先說字節流,要輸出“中國",給輸出流的必須是轉換為utf-8的“中國”,還要告訴瀏覽器,用utf8來解析數據
- //這句話的意思,是讓瀏覽器用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");
- //這句話的意思,是讓瀏覽器用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