Java Servlet輸出中文亂碼問題解決方案
1.現象:字節(jié)流向瀏覽器輸出中文,可能會亂碼(IE低版本)
private void byteMethod(HttpServletResponse response) throws IOException, UnsupportedEncodingException {
String date = "你好";
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(date.getBytes();
}
原因:服務器端和瀏覽器端的編碼格式不一致。
解決方法:服務器端和瀏覽器端的編碼格式保持一致
private void byteMethod(HttpServletResponse response) throws IOException, UnsupportedEncodingException {
String date = "你好";
ServletOutputStream outputStream = response.getOutputStream();
// 瀏覽器端的編碼
response.setHeader("Content-Type", "text/html;charset=utf-8");
// 服務器端的編碼
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");
// 服務器端的編碼
outputStream.write(date.getBytes("utf-8"));
}
2.現象:字符流向瀏覽器輸出中文出現 ???亂碼
private void charMethod(HttpServletResponse response) throws IOException {
String date = "你好";
PrintWriter writer = response.getWriter();
writer.write(date);
}
原因:表示采用ISO-8859-1編碼形式,該編碼不支持中文
解決辦法:同樣使瀏覽器和服務器編碼保持一致
private void charMethod(HttpServletResponse response) throws IOException {
// 處理服務器編碼
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);
}
總結:解決中文亂碼問題使用方法 response.setContentType("text/html;charset=utf-8");可解決字符和字節(jié)的問題。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
mybatis+springboot發(fā)布postgresql數據的實現
本文主要介紹了mybatis+springboot發(fā)布postgresql數據的實現,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-11-11
如何使用Spring Security手動驗證用戶的方法示例
這篇文章主要介紹了如何使用Spring Security手動驗證用戶的方法示例,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-05-05

