Servlet 通过Filter拦截器解决全站编码问题

in Java with 0 comment

Servlet 通过Filter解决全站编码问题

创建代理类

package cn.facade;
import    java.util.regex.Matcher;
import java.util.regex.Matcher;
import    java.util.regex.Pattern;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.UnsupportedEncodingException;


public class CharSetHttpRequest extends HttpServletRequestWrapper {

    public CharSetHttpRequest(HttpServletRequest request) {
        super(request);
    }

    @Override
    public String getParameter(String name) {

        ServletContext context = getServletContext();//获取ServletContext
        String value = super.getParameter(name);//获取参数

        // 正则判断Tomcat版本
       String reg = ".*(Tomcat/8).*";

       String ServerInfo = context.getServerInfo();

       Pattern pattern = Pattern.compile(reg);

        Matcher matcher = pattern.matcher(ServerInfo);

        //如果是Tomcat8的版本则不进行编码转换
       if(!matcher.find()){
           // 判断是否Get方式
           if(getMethod().equalsIgnoreCase("GET")){
               try {
                   // 转换编码
                   value = new String(value.getBytes("iso-8859-1"),"utf-8");
               } catch (UnsupportedEncodingException e) {
                   e.printStackTrace();
               }

           }
       }

       return value;
    }
}

创建拦截器

package cn.alone88;

import cn.facade.CharSetHttpRequest;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(filterName = "CharSetFilter")
public class CharSetFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        CharSetHttpRequest request = new CharSetHttpRequest((HttpServletRequest) req);
        chain.doFilter(request, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}

编辑web.xml 实现全站拦截

<filter>
        <filter-name>charset</filter-name>
        <filter-class>cn.alone88.CharSetFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>charset</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

这样所有的请求都会先拦截处理后在进入Servlet

Responses