Java Servlet輸出中文亂碼問(wèn)題解決方案
1.現(xiàn)象:字節(jié)流向?yàn)g覽器輸出中文,可能會(huì)亂碼(IE低版本)
private void byteMethod(HttpServletResponse response) throws IOException, UnsupportedEncodingException { String date = "你好"; ServletOutputStream outputStream = response.getOutputStream(); outputStream.write(date.getBytes(); }
原因:服務(wù)器端和瀏覽器端的編碼格式不一致。
解決方法:服務(wù)器端和瀏覽器端的編碼格式保持一致
private void byteMethod(HttpServletResponse response) throws IOException, UnsupportedEncodingException { String date = "你好"; ServletOutputStream outputStream = response.getOutputStream(); // 瀏覽器端的編碼 response.setHeader("Content-Type", "text/html;charset=utf-8"); // 服務(wù)器端的編碼 outputStream.write(date.getBytes("utf-8")); }
或者簡(jiǎn)寫如下
private void byteMethod(HttpServletResponse response) throws IOException, UnsupportedEncodingException { String date = "你好"; ServletOutputStream outputStream = response.getOutputStream(); // 瀏覽器端的編碼 response.setContentType("text/html;charset=utf-8"); // 服務(wù)器端的編碼 outputStream.write(date.getBytes("utf-8")); }
2.現(xiàn)象:字符流向?yàn)g覽器輸出中文出現(xiàn) ???亂碼
private void charMethod(HttpServletResponse response) throws IOException { String date = "你好"; PrintWriter writer = response.getWriter(); writer.write(date); }
原因:表示采用ISO-8859-1編碼形式,該編碼不支持中文
解決辦法:同樣使瀏覽器和服務(wù)器編碼保持一致
private void charMethod(HttpServletResponse response) throws IOException { // 處理服務(wù)器編碼 response.setCharacterEncoding("utf-8"); // 處理瀏覽器編碼 response.setHeader("Content-Type", "text/html;charset=utf-8"); String date = "中國(guó)"; PrintWriter writer = response.getWriter(); writer.write(date); }
注意!setCharacterEncoding()方法要在寫入之前使用,否則無(wú)效?。?!
或者簡(jiǎn)寫如下
private void charMethod(HttpServletResponse response) throws IOException { response.setContentType("text/html;charset=GB18030"); String date = "中國(guó)"; PrintWriter writer = response.getWriter(); writer.write(date); }
總結(jié):解決中文亂碼問(wèn)題使用方法 response.setContentType("text/html;charset=utf-8");可解決字符和字節(jié)的問(wèn)題。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
mybatis+springboot發(fā)布postgresql數(shù)據(jù)的實(shí)現(xiàn)
本文主要介紹了mybatis+springboot發(fā)布postgresql數(shù)據(jù)的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-11-11postgresql 實(shí)現(xiàn)16進(jìn)制字符串轉(zhuǎn)10進(jìn)制數(shù)字
這篇文章主要介紹了postgresql 實(shí)現(xiàn)16進(jìn)制字符串轉(zhuǎn)10進(jìn)制數(shù)字操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-02-02Java中g(shù)etResourceAsStream用法分析
這篇文章主要介紹了Java中g(shù)etResourceAsStream用法,較為詳細(xì)的分析了getResourceAsStream的功能及用法,需要的朋友可以參考下2015-06-06mybatis-plus多表聯(lián)查join的實(shí)現(xiàn)
本文主要介紹了mybatis-plus多表聯(lián)查join的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01如何使用Spring Security手動(dòng)驗(yàn)證用戶的方法示例
這篇文章主要介紹了如何使用Spring Security手動(dòng)驗(yàn)證用戶的方法示例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-05-05