Java Servlet輸出中文亂碼問題解決方案
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()方法要在寫入之前使用,否則無效!??!
或者簡(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é):解決中文亂碼問題使用方法 response.setContentType('text/html;charset=utf-8');可解決字符和字節(jié)的問題。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. xml中的空格之完全解說2. asp讀取xml文件和記數(shù)3. IE6/IE7/IE8/IE9中tbody的innerHTML不能賦值的完美解決方案4. 利用CSS制作3D動(dòng)畫5. jsp+servlet簡(jiǎn)單實(shí)現(xiàn)上傳文件功能(保存目錄改進(jìn))6. 匹配模式 - XSL教程 - 47. WML語言的基本情況8. 小技巧處理div內(nèi)容溢出9. jsp cookie+session實(shí)現(xiàn)簡(jiǎn)易自動(dòng)登錄10. xpath簡(jiǎn)介_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
