struts2学习-简单的拦截器

第一个接口:

package com.struts2.interceptorDemo;


/**
 * @author Administrator
 *
 */
public interface Dog {
//两个方法的声明
   public void info();
   public void run(); 
}

接口的实现类

package com.struts2.interceptorDemo;


/**
 * @author Administrator
 *
 */
public class DogImpl implements Dog{


public void info() {
     System.out.println("INFO");
}


public void run() {
System.out.println("RUN");
}


}

拦截器的定义

package com.struts2.interceptorDemo;


public class DogInterceptor {
   //第一个拦截器
public void method1(){
System.out.println("模拟方法1");
}
//第二个拦截器
public void method2(){
System.out.println("模拟方法1");
}
}

代理工厂

package com.struts2.interceptorDemo;


import java.lang.reflect.Proxy;


public class MyProxyFactory {
    public static Object getProxy(Object o){
   
    ProxyHandle handle=new ProxyHandle();
   
    handle.setTarget(o);
   
    return Proxy.newProxyInstance(DogImpl.class.getClassLoader(), o.getClass().getInterfaces(), handle);
    }
}

handle类

/**
 * 
 */
package com.struts2.interceptorDemo;


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;


/**
 * @author Administrator
 *
 */
public class ProxyHandle implements InvocationHandler {

    private Object target;
    DogInterceptor dogInterceptor=new DogInterceptor();
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result=null;
if(method.getName().equals("INFO")){
dogInterceptor.method1();
result=method.invoke(target, args);
dogInterceptor.method2();
}else{
result=method.invoke(target, args);
}
return result;
}
public void setTarget(Object o) {
this.target = o;
}


}


测试类

/**
 * 
 */
package com.struts2.interceptorDemo;


/**
 * @author Administrator
 *
 */
public class TestDog {


/**
* @param args
*/
public static void main(String[] args) {
//创建一个实例
          Dog dogProxy=new DogImpl();
          Dog dog=null;
          Object proxy=MyProxyFactory.getProxy(dogProxy);
          if(proxy instanceof Dog){
         dog=(Dog)proxy;
          }
          dog.info();
          dog.run();



}


欢迎关注公众号:Java后端技术全栈