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上面来,则也需要特殊注意这个问题,可能要删减代码中响应乱码的处理模块了。

  • 相关阅读:
    Auto X2021 K Increasing Sequence
    拉普拉斯平滑处理 Laplace Smoothing
    博学之
    Python-生成音乐-pyshnth
    Python-Kivy ImportError: DLL load failed: 找不到指定的模块
    Python-Word模板填充-docxtpl
    Python-文字转语音-pyttsx3
    Virtual Box中Ubuntu使用"桥接网卡"不能联网而使用"网络地址转换(NAT)"却可以上网
    STM32的HAL库中的DMA_FLAG_TCIF3_7等几个宏定义的含义
    Linux下编写互相通信的驱动模块并将其加入到内核中
  • 原文地址:https://www.cnblogs.com/guo-rong/p/7611883.html
Copyright © 2011-2022 走看看