让咱们再来回顾一下以前咱们曾经用过的一张Action LifeCycle(生命周期)的图: java
图中,咱们能够发现,Struts2的Interceptor一层一层,把Action包裹在最里面。这样的结构,大概有如下一些特色:
1. 整个结构就如同一个堆栈,除了Action之外,堆栈中的其余元素是Interceptor
2. Action位于堆栈的底部。因为堆栈"先进后出"的特性,若是咱们试图把Action拿出来执行,咱们必须首先把位于Action上端的Interceptor拿出来执行。这样,整个执行就造成了一个递归调用
3. 每一个位于堆栈中的Interceptor,除了须要完成它自身的逻辑,还须要完成一个特殊的执行职责。这个执行职责有3种选择:
程序员
Struts2的拦截器结构的设计,其实是一个典型的责任链模式的应用。首先将整个执行划分红若干相同类型的元素,每一个元素具有不一样的逻辑责任,并将他们归入到一个链式的数据结构中(咱们能够把堆栈结构也看做是一个递归的链式结构),而每一个元素又有责任负责链式结构中下一个元素的执行调用。
这样的设计,从代码重构的角度来看,其实是将一个复杂的系统,分而治之,从而使得每一个部分的逻辑可以高度重用并具有高度可扩展性。因此,Interceptor结构实在是Struts2/Xwork设计中的精华之笔。数据结构
Interceptor的定义
咱们来看一下Interceptor的接口的定义:app
public interface Interceptor extends Serializable { /** * Called to let an interceptor clean up any resources it has allocated. */ void destroy(); /** * Called after an interceptor is created, but before any requests are processed using * {@link #intercept(com.opensymphony.xwork2.ActionInvocation) intercept} , giving * the Interceptor a chance to initialize any needed resources. */ void init(); /** * Allows the Interceptor to do some processing on the request before and/or after the rest of the processing of the * request by the {@link ActionInvocation} or to short-circuit the processing and just return a String return code. * * @return the return code, either returned from {@link ActionInvocation#invoke()}, or from the interceptor itself. * @throws Exception any system-level error, as defined in {@link com.opensymphony.xwork2.Action#execute()}. */ String intercept(ActionInvocation invocation) throws Exception; }
Interceptor的接口定义没有什么特别的地方,除了init和destory方法之外,intercept方法是实现整个拦截器机制的核心方法。而它所依赖的参数ActionInvocation则是咱们以前章节中曾经提到过的著名的Action调度者。
咱们再来看看一个典型的Interceptor的抽象实现类: 框架
public abstract class AroundInterceptor extends AbstractInterceptor { /* (non-Javadoc) * @see com.opensymphony.xwork2.interceptor.AbstractInterceptor#intercept(com.opensymphony.xwork2.ActionInvocation) */ @Override public String intercept(ActionInvocation invocation) throws Exception { String result = null; before(invocation); // 调用下一个拦截器,若是拦截器不存在,则执行Action result = invocation.invoke(); after(invocation, result); return result; } public abstract void before(ActionInvocation invocation) throws Exception; public abstract void after(ActionInvocation invocation, String resultCode) throws Exception; }
在这个实现类中,实际上已经实现了最简单的拦截器的雏形。或许你们对这样的代码还比较陌生,这没有关系。我在这里须要指出的是一个很重要的方法invocation.invoke()。这是ActionInvocation中的方法,而ActionInvocation是Action调度者,因此这个方法具有如下2层含义:
1. 若是拦截器堆栈中还有其余的Interceptor,那么invocation.invoke()将调用堆栈中下一个Interceptor的执行。
2. 若是拦截器堆栈中只有Action了,那么invocation.invoke()将调用Action执行。
因此,咱们能够发现,invocation.invoke()这个方法实际上是整个拦截器框架的实现核心。基于这样的实现机制,咱们还能够获得下面2个很是重要的推论:
1. 若是在拦截器中,咱们不使用invocation.invoke()来完成堆栈中下一个元素的调用,而是直接返回一个字符串做为执行结果,那么整个执行将被停止。
2. 咱们能够以invocation.invoke()为界,将拦截器中的代码分红2个部分,在invocation.invoke()以前的代码,将会在Action以前被依次执行,而在invocation.invoke()以后的代码,将会在Action以后被逆序执行。
由此,咱们就能够经过invocation.invoke()做为Action代码真正的拦截点,从而实现AOP。
Interceptor拦截类型
从上面的分析,咱们知道,整个拦截器的核心部分是invocation.invoke()这个函数的调用位置。事实上,咱们也正式根据这句代码的调用位置,来进行拦截类型的区分的。在Struts2中,Interceptor的拦截类型,分红如下三类:
1. before
before拦截,是指在拦截器中定义的代码,它们存在于invocation.invoke()代码执行以前。这些代码,将依照拦截器定义的顺序,顺序执行。
2. after
after拦截,是指在拦截器中定义的代码,它们存在于invocation.invoke()代码执行以后。这些代码,将一招拦截器定义的顺序,逆序执行。
3. PreResultListener
有的时候,before拦截和after拦截对咱们来讲是不够的,由于咱们须要在Action执行完以后,可是尚未回到视图层以前,作一些事情。Struts2一样支持这样的拦截,这种拦截方式,是经过在拦截器中注册一个PreResultListener的接口来实现的。 ide
public interface PreResultListener { /** * This callback method will be called after the Action execution and before the Result execution. * * @param invocation * @param resultCode */ void beforeResult(ActionInvocation invocation, String resultCode); }
在这里,咱们看到,Struts2可以支持如此多的拦截类型,与其自己的数据结构和总体设计有很大的关系。正如我在以前的文章中所提到的: 函数
由于Action是一个普通的Java类,而不是一个Servlet类,彻底脱离于Web容器,因此咱们就可以更加方便地对Control层进行合理的层次设计,从而抽象出许多公共的逻辑,并将这些逻辑脱离出Action对象自己。ui
咱们能够看到,Struts2对于整个执行的划分,从Interceptor到Action一直到Result,每一层都职责明确。不只如此,Struts2还为每个层次以前都设立了恰如其分的插入点。使得整个Action层的扩展性获得了前所未有的提高。
Interceptor执行顺序
Interceptor的执行顺序或许是咱们在整个过程当中最最关心的部分。根据上面所提到的概念,咱们实际上已经可以大体明白了Interceptor的执行机理。咱们来看看Struts2的Reference对Interceptor执行顺序的一个形象的例子。
若是咱们有一个interceptor-stack的定义以下: this
<interceptor-stack name="xaStack"> <interceptor-ref name="thisWillRunFirstInterceptor"/> <interceptor-ref name="thisWillRunNextInterceptor"/> <interceptor-ref name="followedByThisInterceptor"/> <interceptor-ref name="thisWillRunLastInterceptor"/> </interceptor-stack>
整个拦截器栈的执行顺序为spa
在这里,我稍微改了一下Struts2的Reference中的执行顺序示例,使得整个执行顺序更加可以被理解。咱们能够看到,递归调用保证了各类各样的拦截类型的执行可以层次分明。
请注意在这里,每一个拦截器中的代码的执行顺序,在Action以前,拦截器的执行顺序与堆栈中定义的一致;而在Action和Result以后,拦截器的执行顺序与堆栈中定义的顺序相反。
接下来咱们就来看看源码,看看Struts2是如何保证拦截器、Action与Result三者之间的执行顺序的。
以前我曾经提到,ActionInvocation是Struts2中的调度器,因此事实上,这些代码的调度执行,是在ActionInvocation的实现类中完成的,这里,我抽取了DefaultActionInvocation中的invoke()方法,它将向咱们展现一切。
/** * @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的行为。
在这里,须要特别强调的,是其中拦截器部分的执行调用:
resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this);
表面上,它只是执行了拦截器中的intercept方法,若是咱们结合拦截器来看,就能看出点端倪来:
public String intercept(ActionInvocation invocation) throws Exception { String result = null; before(invocation); // 调用invocation的invoke()方法,在这里造成了递归调用 result = invocation.invoke(); after(invocation, result); return result; }
原来在intercept()方法又对ActionInvocation的invoke()方法进行递归调用,ActionInvocation循环嵌套在intercept()中,一直到语句result = invocation.invoke()执行结束。这样,Interceptor又会按照刚开始执行的逆向顺序依次执行结束。
一个有序链表,经过递归调用,变成了一个堆栈执行过程,将一段有序执行的代码变成了2段执行顺序彻底相反的代码过程,从而巧妙地实现了AOP。这也就成为了Struts2的Action层的AOP基础。