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編寫,簡化開發流程使程序更加易於測試。