免费视频淫片aa毛片_日韩高清在线亚洲专区vr_日韩大片免费观看视频播放_亚洲欧美国产精品完整版

打開APP
userphoto
未登錄

開通VIP,暢享免費(fèi)電子書等14項(xiàng)超值服

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

基礎(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é)果

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é)果

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é)果

思考?

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

Demo1亂碼的原因

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

反觀Demo2,并沒有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就可以明白了:

也就是說(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亂碼的方法!

本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊舉報(bào)。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
eclipse tomcat8 環(huán)境下JSP文件中文亂碼問題
生活服務(wù)
分享 收藏 導(dǎo)長(zhǎng)圖 關(guān)注 下載文章
綁定賬號(hào)成功
后續(xù)可登錄賬號(hào)暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點(diǎn)擊這里聯(lián)系客服!

聯(lián)系客服