码迷,mamicode.com
首页 > 其他好文 > 详细

struts2模拟拦截器实现的小例子

时间:2015-05-02 20:46:01      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

  1.拦截器接口

public interface Interceptor {
    void interceptor(ActionInvocation invocation);
}

  2.给接口做3个实现

public class FirstInterceptor implements Interceptor {
    public void interceptor(ActionInvocation invocation) {
        System.out.println(1);
        invocation.invoke();
        System.out.println(-1);
    }
}

public class SecondInterceptor implements Interceptor{
    public void interceptor(ActionInvocation invocation) {
        System.out.println(2);
        invocation.invoke();
        System.out.println(-2);
    }
}

public class ThirdInterceptor implements Interceptor{
    public void interceptor(ActionInvocation invocation) {
        System.out.println(3);
        invocation.invoke();
        System.out.println(-3);
    }
}

  3.一个Action对象

public class Action {
    public void execute(){
        System.out.println("execute执行了!!!");
    }
}

  4.ActionInvocation在初始化的时候,把3个拦截器的实现初始化到List里,模拟拦截器栈

 1 public class ActionInvocation {
 2     List<Interceptor> interceptors = new ArrayList<Interceptor>();
 3     int index = -1;
 4     Action a = new Action();
 5     
 6     public ActionInvocation(){
 7         this.interceptors.add(new FirstInterceptor());
 8         this.interceptors.add(new SecondInterceptor());
 9         this.interceptors.add(new ThirdInterceptor());
10     }
11     public void invoke() {
12         index++;
13         
14         if (index >= this.interceptors.size()) {
15             a.execute();
16         } else {
17             this.interceptors.get(index).interceptor(this);
18         }
19     }
20 }

  5.运行

public class Main {
    public static void main(String[] args) {
        new ActionInvocation().invoke();
    }
}

  6.结果

1
2
3
execute执行了!!!
-3
-2
-1  

 

struts2模拟拦截器实现的小例子

标签:

原文地址:http://www.cnblogs.com/yanghyun/p/4472447.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!