• tomcat解决GET请求中文参数乱码


    通常,在使用Spring MVC框架的应用程序中,为了解决中文参数乱码的问题,都会添加如下过滤器配置:

    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


    但是,在Tomcat下运行时,对于GET请求参数的处理和POST参数不同,会出现POST中文参数正常,但是GET请求中文参数乱码的情形。
    通过查看Tomcat相关源码得知,为了处理GET请求中的中文参数乱码问题,必须明确设置Connector的URIEncoding属性为指定编码。
    具体配置如下:

    <Connector port="8000" protocol="HTTP/1.1"
                   connectionTimeout="20000"
                   redirectPort="8443" URIEncoding="utf-8"/>

    org.apache.catalina.connector.CoyoteAdapter类service()方法源码片段如下:

    @Override
    public void service(org.apache.coyote.Request req, org.apache.coyote.Response res)
            throws Exception {
    
        Request request = (Request) req.getNote(ADAPTER_NOTES);
        Response response = (Response) res.getNote(ADAPTER_NOTES);
    
        if (request == null) {
            // Create objects
            request = connector.createRequest();
            request.setCoyoteRequest(req);
            response = connector.createResponse();
            response.setCoyoteResponse(res);
    
            // Link objects
            request.setResponse(response);
            response.setRequest(request);
    
            // Set as notes
            req.setNote(ADAPTER_NOTES, request);
            res.setNote(ADAPTER_NOTES, response);
    
            // Set query string encoding
            req.getParameters().setQueryStringEncoding(connector.getURIEncoding()); // 显然,在处理GET查询参数编码时是获取Connector的URIEncoding属性
        }
        ...
    }
  • 相关阅读:
    将微信小程序上传到公司的账号下
    当HBuilderX运行时打不开微信开发者工具时
    vue路径中去掉#
    初次快速使用git
    小米商城应用效果(阴影效果)
    如何使用hover点击一个元素使另一个颜色变色
    Open browser failed!! Please check if you have installed the browser correct
    vue中解决跨域问题
    vue中如何实现点击动态切换样式
    es5中数组的迭代方法 forEach,map,filter,some,every
  • 原文地址:https://www.cnblogs.com/nuccch/p/6756238.html
Copyright © 2020-2023  润新知