从doFilter开始执行,流程如图。
下面是Struts2官方的图。
这其中主要要解释的就是重复调用一个个interceptor(是从配置文件中读取的),当全部调用完成后,再调用Action。
下面我们用一个小项目来模拟一下,就很好理解了(项目中的类名和Struts2中的相同或类似)。
我们新建了一个Java Project。
代码如下。
public class Action { public void execute(){ System.out.println("execute!"); } }
import java.util.ArrayList; import java.util.List; public class ActionInvocation { List<Interceptor> interceptors = new ArrayList<Interceptor>(); int index = -1; Action a = new Action(); public ActionInvocation(){ this.interceptors.add(new FirstInterceptor()); this.interceptors.add(new SecondInterceptor()); } public void invoke(){ index++; if(index >= interceptors.size()){ a.execute(); } else { this.interceptors.get(index).intercept(this); } } }
public class FirstInterceptor implements Interceptor{ @Override public void intercept(ActionInvocation incocation) { System.out.println(1); incocation.invoke(); System.out.println(-1); } }
public class SecondInterceptor implements Interceptor{ @Override public void intercept(ActionInvocation incocation) { System.out.println(2); incocation.invoke(); System.out.println(-2); } }
public interface Interceptor { public void intercept(ActionInvocation incocation); }
public class Main { public static void main(String args[]){ new ActionInvocation().invoke(); } }
我们可以从结果中看到,进入FirstInterceptor中被拦截,然后调用SecondInterceptor,然后调用Action,再返回SecondInterceptor中,再进入FirstInterceptor,这是方法的执行过程,在Struts2中是调用配置文件中的interceptor,而在我们这个项目中是手动add的。
过程可以看图。