Java Servlet輸出中文亂碼問題解決方案
1.現(xiàn)象:字節(jié)流向?yàn)g覽器輸出中文,可能會亂碼(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')); }
或者簡寫如下
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 = '中國'; PrintWriter writer = response.getWriter(); writer.write(date); }
注意!setCharacterEncoding()方法要在寫入之前使用,否則無效!!!
或者簡寫如下
private void charMethod(HttpServletResponse response) throws IOException { response.setContentType('text/html;charset=GB18030'); String date = '中國'; PrintWriter writer = response.getWriter(); writer.write(date); }
總結(jié):解決中文亂碼問題使用方法 response.setContentType('text/html;charset=utf-8');可解決字符和字節(jié)的問題。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. python實(shí)現(xiàn)讀取類別頻數(shù)數(shù)據(jù)畫水平條形圖案例2. python中PyQuery庫用法分享3. python操作數(shù)據(jù)庫獲取結(jié)果之fetchone和fetchall的區(qū)別說明4. Ajax實(shí)現(xiàn)頁面無刷新留言效果5. PHP獲取時(shí)間戳等相關(guān)函數(shù)匯總6. JSP+Servlet實(shí)現(xiàn)文件上傳到服務(wù)器功能7. 阿里前端開發(fā)中的規(guī)范要求8. 關(guān)于HTML5的img標(biāo)簽9. CSS3實(shí)現(xiàn)動態(tài)翻牌效果 仿百度貼吧3D翻牌一次動畫特效10. ASP中解決“對象關(guān)閉時(shí),不允許操作。”的詭異問題……
