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')); }
或者簡寫如下
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)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. python全棧開發(fā)語法總結(jié)2. Python調(diào)用接口合并Excel表代碼實(shí)例3. Python如何批量生成和調(diào)用變量4. ASP.Net Core對(duì)USB攝像頭進(jìn)行截圖5. 如何在Python項(xiàng)目中引入日志6. 通過CSS數(shù)學(xué)函數(shù)實(shí)現(xiàn)動(dòng)畫特效7. python b站視頻下載的五種版本8. Python快速將ppt制作成配音視頻課件的操作方法9. ASP.Net Core(C#)創(chuàng)建Web站點(diǎn)的實(shí)現(xiàn)10. ajax動(dòng)態(tài)加載json數(shù)據(jù)并詳細(xì)解析
