相信很多同學和我一樣遇到過在通過伺服器響應介面介面瀏覽器介面出現亂碼的問題吧,今天我們就來思考一下如何解決亂碼問題。
亂碼產生的原因:
1.Servlet程式輸出給瀏覽器的內容,不是任何一種中文字元集編碼
2.瀏覽器瀏覽網頁文檔是所有採用的字元集編碼與它接收到的中文字元集本身的字元編碼不一致。
view plain copy to clipboard print ? //response對象 因為getbytes對象擷取的是gb2312的資料,而瀏覽器採用的預設編碼是gb2312,所以就不會出現亂碼 //response對象 因為getbytes對象擷取的是gb2312的資料,而瀏覽器採用的預設編碼是gb2312,所以就不會出現亂碼
view plain copy to
clipboard print ?
<pre name="code" class="java" style="margin-top: 4px; margin-right: 0px; margin-bottom: 4px; margin-left: 0px; background-color: rgb(240, 240, 240); ">response.getOutputStream().write("賢賢學java".getBytes()); <pre name="code" class="java" style="margin-top: 4px; margin-right: 0px; margin-bottom: 4px; margin-left: 0px; background-color: rgb(240, 240, 240); ">response.getOutputStream().write("賢賢學java".getBytes());//如果我們把預設編碼設定成為UTF-8,那麼我們會發現,瀏覽器又出現了編碼問題,這就是第二種產生原因所導致的,下面有兩種方式解決:/*第一種*/response.setHeader("Content-Type",
"text/html;charset=utf-8");
view plain copy to clipboard print ? view plain copy to clipboard print ? <pre name="code" class="java" style="margin-top: 4px; margin-right: 0px; margin-bottom: 4px; margin-left: 0px; background-color: rgb(240, 240, 240); ">/*第二種*/response.getOutputStream().write("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">".getBytes()); <pre name="code" class="java" style="margin-top: 4px; margin-right: 0px; margin-bottom: 4px; margin-left: 0px; background-color: rgb(240, 240, 240); ">/*第二種*/response.getOutputStream().write("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">".getBytes());
view plain copy to clipboard print ? response.getOutputStream().write("中國".getBytes("UTF-8")); /*OutPutStream流在瀏覽器上輸出數字*/ response.getOutputStream().write((98+"").getBytes()); response.getOutputStream().write("中國".getBytes("UTF-8")); /*OutPutStream流在瀏覽器上輸出數字*/ response.getOutputStream().write((98+"").getBytes());