Proxy 动态代理(在过滤器中对request使用动态代理解决接受参数乱码问题)

jdk动态代理对象:Proxy

  Proxy API:

    static Object   newProxyInstance(ClassLoader loader,Class<?>[] interfaces,InvocationHandler ih);  --返回一个指定接口的代理类实例。

       参数一:ClassLoaader  传入一个类加载器即可;

       参数二:Class[] interfaces  传入被增强类所有实现的接口数组;

       参数三:使用匿名内部类实现InvocationHandler接口;

  InvocationHandler  API:

    Object invoke(Object proxy, Method method, Object[] args);  --在代理实例上处理方法调用并返回结果。

      参数一:proxy  生成的代理对象;

      参数二:method  执行的方法对象;

      参数三:args  要执行方法传入的参数;

使用动态代理实现解决乱码的问题(在过滤器中对request使用动态代理)

  

 1 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
 2             throws IOException, ServletException {
 3         HttpServletRequest req =  (HttpServletRequest)request;
 4         HttpServletRequest MyReq = (HttpServletRequest)Proxy.newProxyInstance(req.getClass().getClassLoader(), req.getClass().getInterfaces(), new InvocationHandler() {
 5             @Override
 6             public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
 7                 if ("getParameter".equals(method.getName())) {
 8                     if ("get".equalsIgnoreCase(req.getMethod())) {
 9                         String value = (String)method.invoke(req, args);
10                         value = new String(value.getBytes("iso-8859-1"),"utf-8");
11                         return value;
12                     }else if ("post".equalsIgnoreCase(req.getMethod())) {
13                         req.setCharacterEncoding("utf-8");
14                     }
15                 }
16                 return method.invoke(req, args);
17             }
18         });
19         chain.doFilter(MyReq, response);//将增强后的对象传入过去
20     }

 代理的企业应用:

  spring的AOP:   

    AOP的底层使用的就是代理机制:

    AOP:面向切面编程.新的思想,用来解决OOP中遇到的一些问题!!!

原文地址:https://www.cnblogs.com/laodang/p/9535088.html