Struts2拦截器

拦截器是AOP中的概念,它本身是一段代码,能够通过定义“织入点”,来指定拦截器的代码在“织入点”的前后运行。从而起到拦截的作用。Struts2的Interceptor。其拦截的对象是Action代码。能够定义在Action代码之前或者之后运行拦截器的代码。


首先,我们将重点讨论一下Struts2中的拦截器的内部结构和运行顺序,并结合源代码进行分析。

Interceptor结构

看一下这幅图:

图中,我们能够发现。Struts2的Interceptor一层一层。把Action包裹在最里面。

这种结构,大概有下面一些特点: 

1. 整个结构就如同一个堆栈,除了Action以外,堆栈中的其它元素是Interceptor 

2. Action位于堆栈的底部。因为堆栈"先进后出"的特性,假设我们试图把Action拿出来运行,我们必须首先把位于Action上端的Interceptor拿出来运行。这样,整个运行就形成了一个递归调用 

3. 每一个位于堆栈中的Interceptor。除了须要完毕它自身的逻辑。还须要完毕一个特殊的运行职责。这个运行职责有3种选择:

1) 中止整个运行。直接返回一个字符串作为resultCode 

2) 通过递归调用负责调用堆栈中下一个Interceptor的运行 

3) 假设在堆栈内已经不存在不论什么的Interceptor,调用Action 


Struts2的拦截器结构的设计。实际上是一个典型的责任链模式的应用。

首先将整个运行划分成若干同样类型的元素,每一个元素具备不同的逻辑责任,并将他们纳入到一个链式的数据结构中(我们能够把堆栈结构也看作是一个递归的链式结构),而每一个元素又有责任负责链式结构中下一个元素的运行调用。 

这种设计,从代码重构的角度来看,实际上是将一个复杂的系统,分而治之。从而使得每一个部分的逻辑可以高度重用并具备高度可扩展性。所以。Interceptor结构实在是Struts2/Xwork设计中的精华之笔。

Interceptor运行分析 

Interceptor的定义 

我们来看一下Interceptor的接口的定义: 

Java代码
  1. public interface Interceptor extends Serializable {  
  2.   
  3.     /** 
  4.      * Called to let an interceptor clean up any resources it has allocated. 
  5.      */  
  6.     void destroy();  
  7.   
  8.     /** 
  9.      * Called after an interceptor is created, but before any requests are processed using 
  10.      * {@link #intercept(com.opensymphony.xwork2.ActionInvocation) intercept} , giving 
  11.      * the Interceptor a chance to initialize any needed resources. 
  12.      */  
  13.     void init();  
  14.   
  15.     /** 
  16.      * Allows the Interceptor to do some processing on the request before and/or after the rest of the processing of the 
  17.      * request by the {@link ActionInvocation} or to short-circuit the processing and just return a String return code. 
  18.      * 
  19.      * @return the return code, either returned from {@link ActionInvocation#invoke()}, or from the interceptor itself. 
  20.      * @throws Exception any system-level error, as defined in {@link com.opensymphony.xwork2.Action#execute()}. 
  21.      */  
  22.     String intercept(ActionInvocation invocation) throws Exception;  
  23. }  


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

 

我们再来看看一个典型的Interceptor的抽象实现类: 

Java代码 
  1. public abstract class AroundInterceptor extends AbstractInterceptor {  
  2.       
  3.     /* (non-Javadoc) 
  4.      * @see com.opensymphony.xwork2.interceptor.AbstractInterceptor#intercept(com.opensymphony.xwork2.ActionInvocation) 
  5.      */  
  6.     @Override  
  7.     public String intercept(ActionInvocation invocation) throws Exception {  
  8.         String result = null;  
  9.   
  10.         before(invocation);  
  11.         // 调用下一个拦截器,假设拦截器不存在,则运行Action  
  12.         result = invocation.invoke();  
  13.         after(invocation, result);  
  14.   
  15.         return result;  
  16.     }  
  17.       
  18.     public abstract void before(ActionInvocation invocation) throws Exception;  
  19.   
  20.     public abstract void after(ActionInvocation invocation, String resultCode) throws Exception;  
  21.   
  22. }  


在这个实现类中,实际上已经实现了最简单的拦截器的雏形。也许大家对这种代码还比較陌生。这没有关系。我在这里须要指出的是一个非常重要的方法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的接口来实现的。

 

Java代码 
  1. public interface PreResultListener {  
  2.   
  3.     /** 
  4.      * This callback method will be called after the Action execution and before the Result execution. 
  5.      * 
  6.      * @param invocation 
  7.      * @param resultCode 
  8.      */  
  9.     void beforeResult(ActionInvocation invocation, String resultCode);  
  10. }  


在这里。我们看到,Struts2可以支持如此多的拦截类型,与其本身的数据结构和总体设计有非常大的关系。正如我在之前的文章中所提到的: 

downpour 写道
由于Action是一个普通的Java类,而不是一个Servlet类。全然脱离于Web容器。所以我们就行更加方便地对Control层进行合理的层次设计,从而抽象出很多公共的逻辑,并将这些逻辑脱离出Action对象本身。

我们能够看到,Struts2对于整个运行的划分,从Interceptor到Action一直到Result。每一层都职责明白。不仅如此,Struts2还为每个层次之前都设立了恰如其分的插入点。使得整个Action层的扩展性得到了史无前例的提升。 

Interceptor运行顺序 

Interceptor的运行顺序也许是我们在整个过程中最最关心的部分。

依据上面所提到的概念。我们实际上已经可以大致明确了Interceptor的运行机理。

我们来看看Struts2的Reference对Interceptor运行顺序的一个形象的样例。

 

假设我们有一个interceptor-stack的定义例如以下: 

Xml代码 
  1. <interceptor-stack name="xaStack">  
  2.   <interceptor-ref name="thisWillRunFirstInterceptor"/>  
  3.   <interceptor-ref name="thisWillRunNextInterceptor"/>  
  4.   <interceptor-ref name="followedByThisInterceptor"/>  
  5.   <interceptor-ref name="thisWillRunLastInterceptor"/>  
  6. </interceptor-stack>  


那么,整个运行的顺序大概像这样:


在这里,我略微改了一下Struts2的Reference中的运行顺序演示样例。使得整个运行顺序更加可以被理解。我们可以看到,递归调用保证了各种各样的拦截类型的运行可以井井有条。 

请注意在这里,每一个拦截器中的代码的运行顺序。在Action之前。拦截器的运行顺序与堆栈中定义的一致;而在Action和Result之后。拦截器的运行顺序与堆栈中定义的顺序相反。

 

源代码解析 

接下来我们就来看看源代码,看看Struts2是怎样保证拦截器、Action与Result三者之间的运行顺序的。

 

ActionInvocation是Struts2中的调度器。所以其实,这些代码的调度运行。是在ActionInvocation的实现类中完毕的。这里,我抽取了DefaultActionInvocation中的invoke()方法。它将向我们展示一切。 

Java代码 
  1. /** 
  2.  * @throws ConfigurationException If no result can be found with the returned code 
  3.  */  
  4. public String invoke() throws Exception {  
  5.     String profileKey = "invoke: ";  
  6.     try {  
  7.         UtilTimerStack.push(profileKey);  
  8.               
  9.         if (executed) {  
  10.             throw new IllegalStateException("Action has already executed");  
  11.         }  
  12.         // 依次调用拦截器堆栈中的拦截器代码运行  
  13.         if (interceptors.hasNext()) {  
  14.             final InterceptorMapping interceptor = (InterceptorMapping) interceptors.next();  
  15.             UtilTimerStack.profile("interceptor: "+interceptor.getName(),   
  16.                     new UtilTimerStack.ProfilingBlock<String>() {  
  17.                         public String doProfiling() throws Exception {  
  18.                          // 将ActionInvocation作为參数。调用interceptor中的intercept方法运行  
  19.                             resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this);  
  20.                             return null;  
  21.                         }  
  22.             });  
  23.         } else {  
  24.             resultCode = invokeActionOnly();  
  25.         }  
  26.   
  27.         // this is needed because the result will be executed, then control will return to the Interceptor, which will  
  28.         // return above and flow through again  
  29.         if (!executed) {  
  30.             // 运行PreResultListener  
  31.             if (preResultListeners != null) {  
  32.                 for (Iterator iterator = preResultListeners.iterator();  
  33.                     iterator.hasNext();) {  
  34.                     PreResultListener listener = (PreResultListener) iterator.next();  
  35.                           
  36.                     String _profileKey="preResultListener: ";  
  37.                     try {  
  38.                             UtilTimerStack.push(_profileKey);  
  39.                             listener.beforeResult(this, resultCode);  
  40.                     }  
  41.                     finally {  
  42.                             UtilTimerStack.pop(_profileKey);  
  43.                     }  
  44.                 }  
  45.             }  
  46.   
  47.             // now execute the result, if we're supposed to  
  48.             // action与interceptor运行完成,运行Result  
  49.             if (proxy.getExecuteResult()) {  
  50.                 executeResult();  
  51.             }  
  52.   
  53.             executed = true;  
  54.         }  
  55.   
  56.         return resultCode;  
  57.     }  
  58.     finally {  
  59.         UtilTimerStack.pop(profileKey);  
  60.     }  
  61. }  


从源代码中,我们能够看到,我们之前提到的Struts2的Action层的4个不同的层次,在这种方法中都有体现,他们各自是:拦截器(Interceptor)、Action、PreResultListener和Result。

在这种方法中,保证了这些层次的有序调用和运行。

由此我们也能够看出Struts2在Action层次设计上的众多考虑,每一个层次都具备了高度的扩展性和插入点,使得程序猿能够在不论什么喜欢的层次增加自己的实现机制改变Action的行为。

在这里,须要特别强调的。是当中拦截器部分的运行调用: 

Java代码 
  1. resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this);  


表面上。它仅仅是运行了拦截器中的intercept方法,假设我们结合拦截器来看,就能看出点端倪来: 

Java代码
  1. public String intercept(ActionInvocation invocation) throws Exception {  
  2.     String result = null;  
  3.   
  4.         before(invocation);  
  5.         // 调用invocation的invoke()方法。在这里形成了递归调用  
  6.         result = invocation.invoke();  
  7.         after(invocation, result);  
  8.   
  9.         return result;  
  10. }  


原来在intercept()方法又对ActionInvocation的invoke()方法进行递归调用,ActionInvocation循环嵌套在intercept()中,一直到语句result = invocation.invoke()运行结束。这样,Interceptor又会依照刚開始运行的逆向顺序依次运行结束。

 

一个有序链表,通过递归调用,变成了一个堆栈运行过程。将一段有序运行的代码变成了2段运行顺序全然相反的代码过程。从而巧妙地实现了AOP。这也就成为了Struts2的Action层的AOP基础。


posted @ 2016-01-08 18:53  lcchuguo  阅读(150)  评论(0编辑  收藏  举报