拦截器是一个类,这个类包含方法,用来解决DRY规则,即代码复用的问题。如果不调用拦截器,代码中需要显示通过代码调用目标方法,定义了拦截器,系统就会自动执行。大部分时候,拦截器方法都是通过代理的方式调用的。
例子:动态代理
Dog.java
1: package cc.openhome;
2: public interface Dog {
3: //方法的声明
4: public void info();
5: public void run();
6: }
7:
DogImg.java
1: package cc.openhome;
2: public class DogImpl implements Dog {
3: //提供方法的实现
4: @Override
5: public void info() {
6: // TODO Auto-generated method stub
7: System.out.println("我是一个info猎狗");
8: }
9: @Override
10: public void run() {
11: // TODO Auto-generated method stub
12: System.out.println("我run奔跑迅速");
13: }
14: }
DogIntercepter.java系统拦截器
1: package cc.openhome;
2: public class DogIntercepter {
3: //第一个拦截器方法
4: public void method1(){
5: System.out.println("=====模拟通用方法1======");
6: }
7: //第二个拦截器方法
8: public void method2(){
9: System.out.println("=====模拟通用方法2======");
10: }
11: }
12:
ProxyHandler.java动态调用目标对象的方法
1: package cc.openhome;
2: import java.lang.reflect.InvocationHandler;
3: import java.lang.reflect.Method;
4: public class ProxyHandler implements InvocationHandler {
5: //需被代理的目标
6: private Object target;
7: //用于设置传入目标对象的方法
8: public void setTarget(Object o){
9: this.target=o;
10: }
11: public Object getTarget() {
12: return target;
13: }
14: //创建拦截器实例
15: DogIntercepter di = new DogIntercepter();
16: //执行代理的目标方法时,该invoke方法会被自动调用
17: @Override
18: public Object invoke(Object proxy, Method method, Object[] args)
19: throws Throwable {
20: // TODO Auto-generated method stub
21: Object result = null;
22: //如果被调用方法的方法名为info
23: if(method.getName().equals("info")){
24: di.method1();
25: result = method.invoke(target, args);
26: di.method2();
27: }else{
28: result = method.invoke(target, args);
29: }
30: return result;
31: }
32: }
33:
MyProxyFactory.java代理工厂,作用就是根据目标对象生成一个代理对象
1: package cc.openhome;
2: import java.lang.reflect.Proxy;
3: public class MyProxyFactory {
4: /*
5: * 代理工厂的作用是根据目标对象生成一个代理对象
6: * */
7: public static Object getProxy(Object object){
8: //代理的处理类
9: ProxyHandler handler = new ProxyHandler();
10: //将该Dog实例托付给代理操作
11: handler.setTarget(object);
12: return Proxy.newProxyInstance(DogImpl.class.getClassLoader(), object.getClass().getInterfaces(), handler);
13: }
14: }
15:
TestDog.java主程序
1: package cc.openhome;
2: public class TestDog {
3: public static void main(String[] args){
4: //创建一个Dog实例,该实例将作为被代理的对象
5: Dog targetObject = new DogImpl();
6: Dog dog=null;
7: //以目标对象创建代理
8: Object proxy = MyProxyFactory.getProxy(targetObject);
9: if(proxy instanceof Dog){
10: dog = (Dog)proxy;
11: }
12: //测试代理的方法
13: dog.info();
14: dog.run();
15: }
16: }
17:
运行结果
如果想要知道拦截器具体内容知识,参见Struts2拦截器介绍
当神已无能为力,那便是魔渡众生