小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

Servlet中直接response.getWriter().write() 輸出亂碼解決!

 收藏小管 2017-07-02

基礎(chǔ)環(huán)境

項(xiàng)目編碼:utf-8
頁(yè)面編碼:utf-8
請(qǐng)求類型:Post

Demo1:

Servlet核心代碼

request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");
System.out.println(username);//控制臺(tái)正確輸出中文
response.getWriter().write(username);//頁(yè)面中文亂碼
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

運(yùn)行結(jié)果

這里寫(xiě)圖片描述

Demo2:

Servlet核心代碼

request.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");
System.out.println(username);
request.setAttribute("username", username);
request.getRequestDispatcher("result.jsp").forward(request, response);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

運(yùn)行結(jié)果

這里寫(xiě)圖片描述

Demo3:

Servlet核心代碼

request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
String username = request.getParameter("username");
System.out.println(username);
response.getWriter().write(username);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

運(yùn)行結(jié)果

這里寫(xiě)圖片描述

思考?

為什么Demo1會(huì)出現(xiàn)亂碼?而Demo2沒(méi)有出現(xiàn)亂碼?
明明Demo1的response也設(shè)置了utf-8編碼。

Demo1亂碼的原因

從控制臺(tái)輸出可以看出,控制臺(tái)并沒(méi)有亂碼,只是response在輸出中文的
時(shí)候出現(xiàn)了亂碼,因此,這行代碼:response.setCharacterEncoding(“UTF-8”);
可能并沒(méi)有起到想要的效果。

反觀Demo2,并沒(méi)有response.setCharacterEncoding(“UTF-8”); 這句話,但是輸出的
頁(yè)面是通過(guò)request的轉(zhuǎn)發(fā)到JSP頁(yè)面實(shí)現(xiàn)的。其實(shí)JSP頁(yè)面最后也要轉(zhuǎn)換為Servlet
頁(yè)面中的元素也是response.getWriter().write(“”);出來(lái)的。既然有response,那么
這個(gè)response的編碼是如何確定的呢?我們看一看JSP與對(duì)應(yīng)的Servlet就可以明白了:

這里寫(xiě)圖片描述

也就是說(shuō)Demo2中的response.setCharacterEncoding隱藏在JSP頁(yè)面中了。
然后根據(jù)轉(zhuǎn)換后的Servlet可以看出response.setContentType(“text/html;charset=utf-8”);
才能達(dá)到應(yīng)有的效果,在使用http協(xié)議的情況中,該方法設(shè)置 Content-type實(shí)體報(bào)頭
response.setContentType()的作用是使客戶端瀏覽器,區(qū)分不同種類的數(shù)據(jù),并根據(jù)不
同的MIME調(diào)用瀏覽器內(nèi)不同的程序嵌入模塊來(lái)處理相應(yīng)的數(shù)據(jù)。
例如:web瀏覽器就是通過(guò)MIME類型來(lái)判斷文件是GIF圖片,通過(guò)MIME類型來(lái)處理json字符串。
Tomcat的安裝目錄\conf\web.xml 中就定義了大量MIME類型 ,可以參考。
response.setContentType(“text/html; charset=utf-8”); html
response.setContentType(“text/plain; charset=utf-8”); 文本
response.setContentType(“text/JavaScript; charset=utf-8”); json數(shù)據(jù)
response.setContentType(“application/xml; charset=utf-8”); xml數(shù)據(jù)

因此Demo3正是解決Demo1亂碼的方法!

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買(mǎi)等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多