Fork me on GitHub

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();
}

}

 

最后运行结果是:






posted @ 2012-01-30 17:54  落崖惊风  阅读(2903)  评论(0编辑  收藏  举报