Html表單提交到Servlet輸出到頁面亂碼

來源:互聯網
上載者:User

標籤:style   http   io   ar   os   使用   java   sp   for   

    Html使用的編碼是UTF-8編碼顯示頁面,之後使用form表單提交欄位到Servlet中,Servlet將利用getParamer方法獲得form提交的欄位,之後通過Respone中的writer將擷取到的前台欄位反饋到前台中去,出現中午亂碼錯誤,這是因為添加了這個欄位。    
  1. response.setContentType("text/html");
    可見瀏覽器對後台提交的欄位的一個識別作用,這個欄位代表提交的欄位是“文本/html”,給瀏覽器識別,這樣後台提交文本時候的時候會出現中文字元是以文本的形式提交的,而提交的欄位是使用GBK格式(因為能夠在終端正確顯示)必然因為輸入和輸出資料流的不同,導致中文字元出現編碼問題,所以必須對輸入和輸出資料流進行編碼通化,具體方法就是加如下代碼:
  1. //設定輸入的編碼格式為utf-8
  2. request.setCharacterEncoding("utf8");
  3. //設定輸入的編碼格式為utf-8
  4. response.setCharacterEncoding("utf8");
    完整的操作片段為:
  1. public void doPost(HttpServletRequest request, HttpServletResponse response)
  2. throws ServletException, IOException {
  3. //設定輸入的編碼格式為utf-8
  4. request.setCharacterEncoding("utf8");
  5. //設定輸入的編碼格式為utf-8
  6. response.setCharacterEncoding("utf8");
  7. //給瀏覽器的標示,該字型為text/html
  8. response.setContentType("text/html");
  9. PrintWriter out = response.getWriter();
  10. // 做一些輸出操作...........
  11. // out.println();
  12. out.flush();
  13. out.close();
  14. }
    這樣便能輸出中文了。


來自為知筆記(Wiz)

Html表單提交到Servlet輸出到頁面亂碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.