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
=========================================================