Struts2拦截器的底层实现(AOP思想)

1.目标类接口:

package com.interceptor;

public interface TargetInterface
{
public void doSomething();
}

2.目标类实现:

复制代码
package com.interceptor;

public class Target implements TargetInterface
{
public void doSomething()
{
System.out.println("doSomething");
}
}
复制代码

3.自定义拦截器:

复制代码
package com.interceptor;

public class Interceptor
{

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

public void after()
{
System.out.println("after");
}
}
复制代码

4.将拦截器类和目标代码类结合在一起的处理类:

复制代码
package com.interceptor;

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

public class MyHandler implements InvocationHandler
{

private Object object;
private Interceptor interceptor=new Interceptor();

public void setObject(Object object)
{
this.object=object;
}

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

Object result=null;
interceptor.before();
result=method.invoke(object, args);
interceptor.after();
return result;
}
}
复制代码

5.将目标类进行包装后的代理类:

复制代码
package com.interceptor;
import java.lang.reflect.Proxy;

public class MyProxy
{
public Object getProxy(Object object)
{
MyHandler myHandler=new MyHandler();
myHandler.setObject(object);
return Proxy.newProxyInstance(Target.class.getClassLoader(),object.getClass().getInterfaces(),myHandler);
}
}
复制代码

6.客户端程序测试类:

复制代码
package com.interceptor;

public class Client
{
public static void main(String[] args) {
TargetInterface target=new Target();
MyProxy myProxy=new MyProxy();
TargetInterface proxy=(TargetInterface)myProxy.getProxy(target);
proxy.doSomething();
}

}
复制代码

 

最后运行结果是:

Struts2拦截器的底层实现(AOP思想)

 

你可能感兴趣的:(struts2拦截器)