• http请求中的中文乱码问题


    通过浏览器访问服务器页面和资源时,不可避免地要传送中文字串,如果客户机与服务器不能用同一码表解析字串,肯定会出现各种各样的乱码问题。我总结了几个乱码场景及解决办法,如下

    1、服务器上的中文字串被客户端访问时出现的乱码问题

    原因:浏览器在解析中文时,不知道该用什么码表去解析,就会用默认的gb2312去解析,肯定会出现乱码

    解决办法:以什么码表写入流,在响应的请求头里就告诉浏览器用什么码表,例子使用utf-8

    //告诉浏览器使用UTF-8码表解析
    response.setHeader("Content-type","text/html;charset=UTF-8");//如果写成text/html,charset=UTF-8就会变成了下载,一定要小心
    String data="我是谁“;
    OutputStream out = response.getOutputStream();
    out.write(data.getBytes("UTF-8)); //以UTF-8写入输出流
    //告诉浏览器使用UTF-8码表解析
    response.setHeader("content-type","text/html;charset=UTF-8");
    //告诉response以什么码表向浏览器写出数据
    response.setCharacterEncoding("UTF-8");
    String data="我是谁“;
    OutputStream out = response.getOutputStream();
    out.write(data); 

    上面两种方法的效果是一样的,除了上面两种写法,还有一种更简单的写法,效果同上。

    //告诉浏览器使用UTF-8码表解析
    //告诉response以什么码表向浏览器写出数据
    response.setContentType("text/html;charset=UTF-8");
    String data="我是谁“;
    OutputStream out = response.getOutputStream();
    out.write(data);

    最后一种写法原理与上面三种不一样,这是在html文档里通过meta标签告诉浏览器使用什么码表

    //告诉浏览器使用UTF-8码表解析
    String data="我是谁“;
    OutputStream out = response.getOutputStream();
    out.write("<meta http-equiv='content-type' content='text/html;charset=UTF-8'>".getBytes());
    out.write(data.getBytes("UTF-8)); //以UTF-8写入输出流

     2、客户端提交中文到服务端导致的乱码

    原因:客户端以UTF-8编码,服务端中的request以默认的Iso8859码表解析

    解决办法:告诉request用UTF-8码表解析

         下面我们看看如果告诉request,由于get请求与post请求传参方式不一样,因此在这分开举例

          post请求解决方式

    request.setCharacterEncoding("UTF-8");
    String para = request.getParameter("username");

          get请求解决方式

    String name= request.getParameter("username");
    //以原来的编码解析再以UTF-8编码
    name = new String(name.getBytes("iso8859-1"),"UTF-8");

    注意:post请求处理方式对get请求无效,是因为在get请求中参数是在url路径中出现  

    不过可以通过修改server.xml文件中配置编post请求处理方式适用于get请求,配置文件修改如下:

    <Connector port="8080" protocol="HTTP/1.1"
                connectionTimeout="20000"
                redirectPort="8443"
                useBodyEncodingForURI="true"/>  //让URI编码方式与servlet中request的编码方式一致
  • 相关阅读:
    Python学习札记(十五) 高级特性1 切片
    LeetCode Longest Substring Without Repeating Characters
    Python学习札记(十四) Function4 递归函数 & Hanoi Tower
    single number和变体
    tusen 刷题
    实验室网站
    leetcode 76. Minimum Window Substring
    leetcode 4. Median of Two Sorted Arrays
    leetcode 200. Number of Islands 、694 Number of Distinct Islands 、695. Max Area of Island 、130. Surrounded Regions 、434. Number of Islands II(lintcode) 并查集 、178. Graph Valid Tree(lintcode)
    刷题注意事项
  • 原文地址:https://www.cnblogs.com/lovemo1314/p/7142582.html
Copyright © 2020-2023  润新知