package xwork;
import java.io.Serializable;
/**
* @author wangmingjie
* @date 2008-9-26上午11:09:05
*/
public interface Interceptor extends Serializable {
String intercept(ActionInvocation invocation) throws Exception;
}
==============================================
package xwork;
/**
* @author wangmingjie
* @date 2008-9-26上午11:11:56
*/
public class FirstInterceptor implements Interceptor {
public String intercept(ActionInvocation invocation) throws Exception {
String resultCode = null;
System.out.println("before first Interceptor ");
resultCode = invocation.invoke();
System.out.println("after first Interceptor ");
return resultCode;
}
}
==============================================
package xwork;
/**
* @author wangmingjie
* @date 2008-9-26上午11:13:34
*/
public class SecondInterceptor implements Interceptor {
public String intercept(ActionInvocation invocation) throws Exception {
String resultCode = null;
System.out.println("before second Interceptor ");
resultCode = invocation.invoke();
System.out.println("after second Interceptor ");
return resultCode;
}
}
==================核心調用過程============================
package xwork;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* @author wangmingjie
* @date 2008-9-26上午11:10:00
*/
public class ActionInvocation {
private boolean executed = false;
private String resultCode = null;
private Iterator interceptors;
private void init(){
List<Interceptor> interceptorList = new ArrayList<Interceptor>();
interceptorList.add(new FirstInterceptor());
interceptorList.add(new SecondInterceptor());
interceptors = interceptorList.iterator();
}
public String invoke() throws Exception {
if(executed){
throw new Exception("已經執行了");
}
if (interceptors.hasNext()) {//下面就是核心實現代碼
resultCode = ((Interceptor)interceptors.next()).intercept(ActionInvocation.this);//注意這裡,將自己作為參數傳入,這是一種遞迴的調用方法。
} else {
resultCode = "success";//執行action的方法
System.out.println("執行action");
}
if (!executed) {
System.out.println("執行preResultListener");
executed = true;
}
return null;
}
public static void main(String[] args) throws Exception{
//再進行斷點跟蹤一下。
ActionInvocation ai = new ActionInvocation();
ai.init();
ai.invoke();
}
}
================執行結果如下==============================
before first Interceptor
before second Interceptor
執行action
執行preResultListener
after second Interceptor
after first Interceptor
=========================================================