zoukankan      html  css  js  c++  java
  • tomcat8 编写字符编码Filter过滤器无效问题

    做一个解决全站的字符编码过滤器,过滤器类和配置如下:

    过滤器类:

    package com.charles.web.filter;
    
    import java.io.IOException;
    import java.lang.reflect.Proxy;
    
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class CharacterEncodingFilter implements Filter {
    
        public void destroy() {
        }
    
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
            HttpServletRequest req = (HttpServletRequest) request;
            HttpServletResponse resp = (HttpServletResponse) response;
    
            HttpServletRequest newRequest = (HttpServletRequest) Proxy.newProxyInstance(req.getClass().getClassLoader(),
                    req.getClass().getInterfaces(), (proxy, method, args) -> {
                        if ("getParameter".equals(method.getName())) {
                            String str = (String) method.invoke(req, args);
                            return new String(str.getBytes("iso8859-1"), "utf-8");
                        }
                        return method.invoke(req, args);
                    });
    
            resp.setContentType("text/html;charset=utf-8");
    
            chain.doFilter(newRequest, resp);
    
        }
    
        public void init(FilterConfig fConfig) throws ServletException {
        }
    
    }

    过滤器配置:

    <!-- 解决全站乱码的filter -->
        <filter>
            <display-name>CharacterEncodingFilter</display-name>
            <filter-name>CharacterEncodingFilter</filter-name>
            <filter-class>com.charles.web.filter.CharacterEncodingFilter</filter-class>
        </filter>
        <filter-mapping>
            <filter-name>CharacterEncodingFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>

    但是在前端form的提交方式是get的情况下,得到的仍然是乱码。

                  刚开始一直纠结于过滤器是不是写错了,编码集是不是写错了,但是经过测试,并没有错,过滤器正常运行,

           最后把new String(str.getBytes("iso8859-1"), "utf-8")改为new String(str.getBytes("utf-8"), "utf-8")后台就能得到值,不再是乱码了。最后百度了下,

          说tomcat8默认的编码集是utf-8,tomcat8之前默认的编码集是iso-8859-1,恍然大悟......

    总结:tomcat7及其版本之前默认的编码集是iso-8859-1,tomcat8默认的字符集已经是UTF-8,所以不再需要为request.getParameter()的结果进行转码,不需要编码编码过滤器类了

  • 相关阅读:
    第36课 经典问题解析三
    第35课 函数对象分析
    67. Add Binary
    66. Plus One
    58. Length of Last Word
    53. Maximum Subarray
    38. Count and Say
    35. Search Insert Position
    28. Implement strStr()
    27. Remove Element
  • 原文地址:https://www.cnblogs.com/charleswone/p/10264849.html
Copyright © 2011-2022 走看看