首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

Struts2中的(Interceptor)拦截器的施行顺序

2012-11-07 
Struts2中的(Interceptor)拦截器的执行顺序Interceptor的接口定义没有什么特别的地方,除了init和destory方

Struts2中的(Interceptor)拦截器的执行顺序

Interceptor的接口定义没有什么特别的地方,除了init和destory方法以外,intercept方法是实现整个拦截器机制的核心方法。而它所依赖的参数ActionInvocation则是我们之前章节中曾经提到过的著名的Action调度者

?

/** * @throws ConfigurationException If no result can be found with the returned code */public String invoke() throws Exception {    String profileKey = "invoke: ";    try {    UtilTimerStack.push(profileKey);        if (executed) {    throw new IllegalStateException("Action has already executed");    }        // 依次调用拦截器堆栈中的拦截器代码执行    if (interceptors.hasNext()) {    final InterceptorMapping interceptor = (InterceptorMapping) interceptors.next();    UtilTimerStack.profile("interceptor: "+interceptor.getName(),     new UtilTimerStack.ProfilingBlock<String>() {public String doProfiling() throws Exception {                         // 将ActionInvocation作为参数,调用interceptor中的intercept方法执行    resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this);    return null;}    });    } else {    resultCode = invokeActionOnly();    }    // this is needed because the result will be executed, then control will return to the Interceptor, which will    // return above and flow through again    if (!executed) {            // 执行PreResultListener    if (preResultListeners != null) {    for (Iterator iterator = preResultListeners.iterator();    iterator.hasNext();) {    PreResultListener listener = (PreResultListener) iterator.next();        String _profileKey="preResultListener: ";    try {    UtilTimerStack.push(_profileKey);    listener.beforeResult(this, resultCode);    }    finally {    UtilTimerStack.pop(_profileKey);    }    }    }    // now execute the result, if we're supposed to            // action与interceptor执行完毕,执行Result    if (proxy.getExecuteResult()) {    executeResult();    }    executed = true;    }    return resultCode;    }    finally {    UtilTimerStack.pop(profileKey);    }}

?

?

从源码中,我们可以看到,我们之前提到的Struts2的Action层的4个不同的层次,在这个方法中都有体现,他们分别是:拦截器(Interceptor)、Action、PreResultListener和Result。在这个方法中,保证了这些层次的有序调用和执行。由此我们也可以看出Struts2在Action层次设计上的众多考虑,每个层次都具备了高度的扩展性和插入点,使得程序员可以在任何喜欢的层次加入自己的实现机制改变Action的行为。

热点排行