struts2的Interceptor實現

Interceptor interface
publicinterface Interceptor extends Serializable {
    void destroy();
    void init();
    String intercept(ActionInvocation invocation) throws Exception;
}
init方法是在interceptor被實例化之後,intercept方法調用之前被調用的。主要用來分配資源。

interceptor方法是攔截的主要邏輯,返回一個結果,這個結果用於向另一個web資源提出請求時的參數。

調用ActionInvoaction類型的參數invoke方法將會執行action(如果這個攔截器是棧的最後一個攔截器)

或者另外一個攔截器。
注意:記住result被呼出之後,invoke會返回。如果想在結果被呼出之前做一些其他事情就需要實現PreResultListener。
一個struts2的action實例被每一個request創建,沒有必要線程安全。Interceptors在各requests之間是共享的,必須線程安全。
AbstractInterceptor
AbstractInterceptor類提供init和destroy的空實現,可以被用於這兩個方法沒有需要實現的時候可以繼承
一個攔截器實現的例子
importcom.opensymphony.xwork2.ActionInvocation;
importcom.opensymphony.xwork2.interceptor.AbstractInterceptor;
publicclassSimpleInterceptor extendsAbstractInterceptor {
    publicString intercept(ActionInvocation invocation) throwsException {
       MyAction action = (MyAction)invocation.getAction();
       action.setDate(newDate());
       returninvocation.invoke();
    }
}
翻譯自http://struts.apache.org/docs/writing-interceptors.html
發佈了43 篇原創文章 · 獲贊 2 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章