FilterDispatcher;FilterDispatcher调用Action映射器ActionMapper,ActionMapper决定是否调用action,之后FilterDispatcher将请求转交给ActionProxy;ActionProxy通过Configuation Manager在Struts.xml中搜索被请求的action类。ActionProxy创建一个被请求的action实例,这时如果配置文件中存在与被请求的action相关的拦截器配置,则拦截器将会在action被调用前后得到执行。
拦截器栈是多个拦截器的集合,拦截器栈确定了多个拦截器执行的顺序,便于拦截器的管理。
<interceptors>
<interceptor name= "interceptorA" class="interceptorA">
<interceptor name= "interceptorB" class="interceptorB">
<interceptor-stack name="interceptor-stack">
<interceptor-ref name="interceptorA"/>
<interceptor-ref name="interceptorB"/>
</interceptor-stack>
</interceptors>
struts2允许创建自定义拦截器,定义自定义拦截器需要实现Intercertor接口。此接口包含三个方法。
public interface Interceptor extends Serializabled{
void init();
void destory();
String interceptor(ActionInvocation invocation) throws Exception;
}
init()方法在拦截器执行之前被调用,主要用于初始化系统资源。
destory()方法用于销毁拦截器实例
interoptor()用于实现具体的拦截器操作。
实现自定义拦截器的另一个方法是继承AbstractInterceptor,使用继承AbstractInterceptor方法只需覆盖interceptor()方法即可,
public class Interceptor extends AbstractInterceptor {
public static final long serialVersionUID = "1L";
public String intercept(ActionInvocation actionInvocation) throws Exception {
System.out.println("Interceptor execute !");
String result = Invocation.invoke();
return result();
}
使用拦截器的优点是 增加编程灵活性,是开发人员能够专注于Action编写,简化开发流程使程序更加易于测试。