• Servlet中文乱码解决方法


    程序中的输入输出都是以流的形式保存的,流中保存的实际上全都是字节文件。

    字节流和字符流的区别:

    在Java.io包中操作文件内容的主要有两大类:字节流、字符流,两类都分为输入和输出操作。

    在字节流中输出数据主要是使用OutputStream完成,输入使的是InputStream,主要用来处理字节或二进制对象,字节流处理单元为1个字节,操作字节和字节数组;

    在字符流中输出主要是使用Writer类完成,输入流主要使用Reader类完成,主要用来处理字符或字符串,字符流处理的单元为2个字节的Unicode字符,分别操作字符、字符数组或字符串。

    这四个都是抽象类

    使用字符流输出数字默认被认为是ASCII

    response.getWriter().write(65); 显示结果是 A
    response.getWriter().write(65 + ""); 线上方结果为 65

    字节流输出中文:

    //拿到输出字节流对象
    ServletOutputStream sos = response.getOutputStream();
    byte[] bs = "大家一起去请假!!!".getBytes("UTF-8");
    
    //告诉服务端所用的编码,通知浏览器要查询的码表
    response.setContentType("text/html;charset=UTF-8");
    
    sos.write(bs);

    字符流输出中文

    public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write("不流泪的机场");    
        }

    下载中文文件名的文件

    public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            //拿到文件的真实路径
                String path = getServletContext().getRealPath("/WEB-INF/classes/借贷宝.jpg");
                //创建一个输入流对象
                InputStream is = new FileInputStream(path);
                //处理中文文件名
                String filename = path.substring(path.lastIndexOf("\") + 1);
                System.out.println("处理前的名称:" + filename);
                
                
                ServletOutputStream sos = response.getOutputStream();
                //通知浏览器以下载的方式打开,使用URLEncoder进行编码
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename,"utf-8"));
                response.setHeader("Content-Type", "application/octet-stream");
                byte[] bs = new byte[1024];
                int b = 0;
                while((b = is.read(bs)) != -1){
                    sos.write(bs,0,b);
                }
             is.close();
        }

    String中 == 和 equal方法的区别 

    java中 "==" 是用来比较两个String对象在内存中的存放地址是否相同;

    在String中的equal方法是比较两个String对象的内容是否相同

    请求参数的中文乱码问题:

    post方式:告诉服务器用哪个码表解码

    request.setCharacterEncoding("UTF-8");

    get方式:

    第一种:采用重建字符串方式:name = new String(name.getBytes("iso-8859-1"), "UTF-8");

    第二种:修改服务器的配置文件 servet.xml

    <Connector URIEncoding="UTF-8"/>

  • 相关阅读:
    NS3系列—4———NS3中文教程5:Tweaking NS3
    NS3系列—3———NS3中文:4 概念描述
    NS3系列—2———NS3笔录
    NS3系列—1———NS3中文教程:3下载及编译软件
    How to speed my too-slow ssh login?
    Linux bridge
    使用 GDB 和 KVM 调试 Linux 内核与模块
    How To Set Up A Serial Port Between Two Virtual Machines In VirtualBox
    Linux内核调试环境搭建(基于ubuntu12.04)
    Android
  • 原文地址:https://www.cnblogs.com/taiguyiba/p/6129225.html
Copyright © 2020-2023  润新知