馬士兵struts2視訊教程第七十六集
阿新 • • 發佈:2019-02-11
實現攔截器主要是在actionInvocation裡面,interceptor在構造方法裝載,然後在invoke方法裡面迴圈載入,每個interceptor裡面invoke下一個interceptor,直到action,然後倒著輸出每個interceptor中invoke後面的方法。
package com.ceair.core.util;
public interface Interceptor {
public void interceptor(ActionInvocation invocation);
}
package com.ceair.core.util; public class FirstInterceptor implements Interceptor { public void interceptor(ActionInvocation invocation) { System.out.println("1"); invocation.invoke(); System.out.println("-1"); } }
package com.ceair.core.util;
public class SecondInterceptor implements Interceptor {
public void interceptor(ActionInvocation invocation) {
System.out.println("2");
invocation.invoke();
System.out.println("-2");
}
}
package com.ceair.core.util; public class Action { public void execute() { System.out.println("Action"); } }
package com.ceair.core.util; import java.util.ArrayList; import java.util.List; public class ActionInvocation { List<Interceptor> list = new ArrayList<Interceptor>(); int index = -1; Action a = new Action(); public ActionInvocation() { this.list.add(new FirstInterceptor()); this.list.add(new SecondInterceptor()); } public void invoke() { index ++; if (index >= this.list.size()) { a.execute(); } else { this.list.get(index).interceptor(this); } } }
package com.ceair.core.util;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new ActionInvocation().invoke();
}
}