zoukankan      html  css  js  c++  java
  • SSM学习笔记(6)---拦截器

    问题

    1、什么是拦截器,做什么的

    2、拦截器的逻辑

    3、拦截器的实现

    解决

    1、、

    由于动态代理一般比较难理解,程序设计者会设计一个拦截器接口供开发者使用,开发者只要知道拦截器接口的方法、含义和作用即可

    2、

    开发者提供拦截器,设计者设置拦截器,调用拦截器before()方法

    如果返回是false调用拦截器around()方法

    如果返回是true,反射原来方法

    最后调用拦截器after()方法

    3、

    定义拦截器接口Interceptor

    public interface Interceptor{

    public boolean before(Object proxy,Object target, Method method, Object [] args);

    //在before方法返回false的情况下,调用around方法

    public void around(Object proxy, Object target,Method method,Object [] args);

    public void after(Object proxy,Object target,Method method, Object [] args);

    }

    MyInterceptor

    public class MyInterceptor implements Interceptor{

    public boolean before(Object proxy,Object target,Method method,Object [] args){

    System.err.println("反射方法前的逻辑");

    return false;//不反射被代理对象原有对象

    }

    public void after(Object proxy,Object target,Method method , Object [] args){

    System.err.println("反射方法后逻辑");

    }

    public void around(Object proxy, Object target,Method method,Object [] args){

    System.err.println("取代了被代理对象的方法");

    }

    在JDK动态代理中使用拦截器

    public class InterceptorJdkProxy implements InvocationHandler{

    private Object = null;//真实对象

    private String interceptorClass = null;//拦截器全限定名

    public InterceptorJdkProxy (Object target,String interceptorClass){

    this.target = target ;

    this.interceptorClass = interceptorClass;

    }

    public static Object bind(Object target, String interceptorClass){

    //取得代理对象

    return Proxy.newProxyInstance(target.getClass().getClassLoaser(),

    target.getClass().getInterfaces(),

    new InterceptorJdkProxy(target,interceptorClass());

    }

    public Object invoke(Object target, Method method,Object [] args) throws Throwable{

    if(interceptorClass == null){

    //如果没有设置拦截器则直接反射原来的方法

    return method.invoke(target, args);

    }

    Object result = null;

    //通过反射生成拦截器

    Interceptor interceptor =

    (Incerceptor) Class.forName(interceptorClass).newInstance();

    //调用前置方法

    if(interceptor.before(proxy,target,method,args)){

    //反射原有对象方法

    result = method.invoke(target,args);

    }else{//返回false执行around方法

    interceptor.around(proxy,target,method,args);

    }

    //调用后置方法

    interceptor.after(proxy,target,method,args);

    return result;

    }

    public static void main(String [] args){

    HelloWorld proxy = (HelloWorld) InterceptorJdkProxy.bind(new HelloWorldImpl(),

    "com.lean.ssm.chapter2.interceptor.MyInterceptor");

    proxy.sayHelloWorld();

    }

    会当凌绝顶,一览众山小
  • 相关阅读:
    【译文】不是所有的 bug 都值得修复的
    11月第5周业务风控关注|重磅!瓜子二手车“遥遥领先”被罚天价1250万
    AutoCAD .NET二次开发(四)
    AutoCAD .NET二次开发(三)
    ArcGIS10.2下调试10.1的程序
    再遇1402,注册表权限问题
    ArcGIS Add-in——自动保存编辑
    只打开一个子窗体
    获取编辑器两种方法
    Adobe Acrobat Pro 11安装激活
  • 原文地址:https://www.cnblogs.com/quenvpengyou/p/12820024.html
Copyright © 2011-2022 走看看