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

过滤器类:

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 {
        final 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()的结果进行转码,不需要编码编码过滤器类了

01-14 05:09