动态代理解决全局乱码问题

e cn.itcast.sh.demo;

import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
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;

public class EncodFilter implements Filter{

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, final ServletResponse response,
            final FilterChain chain) throws IOException, ServletException {

        //过滤器需要代理request中的getParameter方法
        final HttpServletRequest httpServletRequest = (HttpServletRequest) request;

        final HttpServletRequest proxyRequest = (HttpServletRequest)Proxy.newProxyInstance(
                EncodFilter.class.getClassLoader(), 
                httpServletRequest.getClass().getInterfaces(), 
                new InvocationHandler() {
                    public Object invoke(Object proxy, Method method, Object[] args)
                            throws Throwable {
                        //获取到调用的方法名
                        String name = method.getName();
                        //判断调用的方法是否是getParameter
                        if( "getParameter".equals(name) ){
                            //进行乱码的处理
                            String requestMehtod = httpServletRequest.getMethod();
                            String value = httpServletRequest.getParameter("name");
                            if( "get".equals(requestMehtod) ){
                                //处理get方式的乱码
                                return new String(value.getBytes("iso-8859-1"),"utf-8");
                            }else{
                                //处理post方式的乱码
                                httpServletRequest.setCharacterEncoding("utf-8");
                                return value;
                            }
                        }else{
                            chain.doFilter(httpServletRequest, response);
                            return null;
                        }
                    }
                });
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub

    }

}

你可能感兴趣的:(JAVAWEB基础,实战篇)