怎麼解決Outputstream亂碼的問題?

來源:互聯網
上載者:User

相信很多同學和我一樣遇到過在通過伺服器響應介面介面瀏覽器介面出現亂碼的問題吧,今天我們就來思考一下如何解決亂碼問題。


亂碼產生的原因:
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());

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.