webwork Interceptor原理

下面我們來看看Interceptor是如何實現在Action執行前後調用的:
ActionInterceptor在框架中的執行,是由ActionInvocation對象調用的。它是用方法:String invoke() throws Exception;來實現的,它首先會依次調用Action對應的Interceptor,執行完成所有的Interceptor之後,再去調用Action的方法,代碼如下:
if (interceptors.hasNext()) {
Interceptor interceptor = (Interceptor) interceptors.next();
resultCode = interceptor.intercept(this);
} else {
     if (proxy.getConfig().getMethodName() == null) {
resultCode = getAction().execute();
} else {
        resultCode = invokeAction(getAction(), proxy.getConfig());
}
}
它會在攔截器棧中遍歷Interceptor,調用Interceptor方法:
String intercept(ActionInvocation invocation) throws Exception;
我們一直都提到,Interceptor是在Action前後執行,可是從上面的代碼我們看到的卻是執行完所有Interceptorintercept()方法之後再去調用我們的Action。“在Action前後執行”是如何實現的呢?我們來看看抽象類AroundInterceptorintercept()實現:
public String intercept(ActionInvocation invocation) throws Exception {
        String result = null;
  
        before(invocation);
        result = invocation.invoke();
        after(invocation, result);
  
        return result;
    }
原來在intercept()方法又對ActionInvocationinvoke()方法進行遞歸調用,ActionInvocation循環嵌套在intercept()中,一直到語句result = invocation.invoke();執行結束,即:Action執行完並返回結果result,這時Interceptor對象會按照剛開始執行的逆向順序依次執行結束。這樣before()方法將在Action執行前調用,after()方法在Action執行之後運行
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章