Java中Servlet輸出中文亂碼問題


1.現象:字節流向瀏覽器輸出中文,可能會亂碼(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");可解決字符和字節的問題。

也可以看一下這位博主的文章,感覺思路很清晰。https://www.cnblogs.com/Survivalist/p/9015754.html

如有問題還望指正!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM