天天看點

[轉] 解決HttpServletResponse輸出的中文亂碼問題

首先,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/simon_1/article/details/9092747