package www.test.web.filter; 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 EncodingFilter implements Filter{ @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final HttpServletRequest req = (HttpServletRequest) request; //使用动态代码解决全局乱码问题 HttpServletRequest enhanceRequset = (HttpServletRequest) Proxy.newProxyInstance( //loader ,和目标类相同的类加载器 request.getClass().getClassLoader(), // interfaces :代表与目标对象实现的所有接口字节码对象数组 request.getClass().getInterfaces(), // h : 具体的操作,InvocationHandler接口 new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //对 getParameter 方法进行增强 String name = method.getName();//获得目标对象的方法名称 if("getParameter".equals(name)){ String invoke = (String) method.invoke(req, args);//乱码 //转码 invoke = new String(invoke.getBytes("iso8859-1"),"UTF-8"); return invoke; } return method.invoke(req, args); } }); chain.doFilter(enhanceRequset, response); } @Override public void destroy() { } }
动态代理:实际开发中一般用于拦截。判断不同的角色,决定是否可以调用这个方法。