zoukankan      html  css  js  c++  java
  • Servlet处理get请求时的中文乱码问题

    使用Servlet处理get请求时,如果get请求的参数中有中文,直接接收会是乱码,这个时候需要使用类似下面的语句来处理乱码:

    String name = request.getParameter("name");
    System.out.prinlnt(name); // 乱码
    // 处理乱码 name = new String(name.getBytes("ISO8859-1"),"UTF-8"); System.out.println(name);// 乱码问题解决

    每次中文都要处理,比较麻烦,可以使用过滤器,使用类型下面的代码处理乱码问题:

    public String getParameter(String name) {
        String value = super.getParameter(name);
        if (value == null)
            return null;
        String method = request.getMethod();
        if ("get".equalsIgnoreCase(method)) {
            try {
                value = new String(value.getBytes("ISO8859-1"),"UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return value;
    }

    为什么我们需要将ISO8859-1转为UTF-8?为什么接收到的参数是ISO8859-1这种编码方式的?
    其实很简单,只是个配置问题:
    在tomcat安装目录下的conf/server.xml中,有如下的配置:

    URIEncoding,该配置决定了使用get请求通过浏览器地址栏访问tomcat时的编码方式,默认的编码方式使ISO8859-1:

    URIEncoding:This specifies the character encoding used to decode the URI bytes, after %xx decoding the URL. If not specified, ISO-8859-1 will be used.
    

    可以这样配置,则上述代码中,就不需要再从ISO8859-1转为UTF-8了:

    URIEncoding="UTF-8"

    值得注意的是,从tomcat8.0开始,URIEncoding默认值不再是ISO8859-1,而变成了UTF-8 

    那么也就意味着,从tomcat8.0开始,get请求中的中文参数,不需要特殊处理了。而如果是tomcat8之前的项目要迁移到tomcat8上面来,则也需要特殊注意这个问题,可能要删减代码中响应乱码的处理模块了。

  • 相关阅读:
    兼容各浏览器,背景透明,内容不透明
    101 个 MySQL 的调节和优化的提示
    二手房买卖砍价最新攻略 帮你花少钱买好房
    “中国互联网100强”(2013)发布
    写入文件,创建xunlei批量任务
    武汉选房
    Java并发编程(十一)线程池的使用
    Retrofit 代理模式
    Java并发编程(十)阻塞队列
    不要在Android的Application对象中缓存数据!
  • 原文地址:https://www.cnblogs.com/guo-rong/p/7611883.html
Copyright © 2011-2022 走看看