zoukankan      html  css  js  c++  java
  • 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

    如有问题还望指正!

  • 相关阅读:
    hive与hbase整合
    待重写
    hive DML
    【知识强化】第六章 总线 6.1 总线概述
    【知识强化】第五章 中央处理器 5.1 CPU的功能和基本结构
    【知识强化】第四章 指令系统 4.3 CISC和RISC的基本概念
    【知识强化】第四章 指令系统 4.2 指令寻址方式
    【知识强化】第四章 指令系统 4.1 指令格式
    【知识强化】第三章 存储系统 3.6 高速缓冲存储器
    【知识强化】第三章 存储系统 3.5 双口RAM和多模块存储器
  • 原文地址:https://www.cnblogs.com/springa/p/12687167.html
Copyright © 2011-2022 走看看