Struts2拦截器原理以及实例

 

1、Struts2拦截器定义程序员

1. Struts2拦截器是在访问某个Action或Action的某个方法,字段以前或以后实施拦截,而且Struts2拦截器是可插拔的,拦截器是AOP的一种实现.app

2. 拦截器栈(Interceptor Stack)。Struts2拦截器栈就是将拦截器按必定的顺序联结成一条链。在访问被拦截的方法或字段时,Struts2拦截器链中的拦截器就会按其以前定义的顺序被调用。框架

2、实现Struts2拦截器原理ide

  Struts 2的拦截器实现相对简单。当请求到达Struts2的ServletDispatcher时,Struts 2会查找配置文件,并根据其配置实例化相对的拦截器对象,而后串成一个列表(list),最后一个一个地调用列表中的拦截器。事实上,咱们之因此可以如此灵活地使用拦截器,彻底归功于“动态代理”的使用。动态代理是代理对象根据客户的需求作出不一样的处理。对于客户来讲,只要知道一个代理对象就好了。函数

那Struts2中,拦截器是如何经过动态代理被调用的呢?当Action请求到来的时候,会由系统的代理生成一个Action的代理对象,由这个代理对象调用Action的execute()或指定的方法,并在struts.xml中查找与该Action对应的拦截器。若是有对应的拦截器,就在Action的方法执行前(后)调用这些拦截器;若是没有对应的拦截器则执行Action的方法。其中系统对于拦截器的调用,是经过ActionInvocation来实现的。代码以下:this

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());  
} }

三.拦截器执行分析spa

     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。code

三.源码解析

        经过查看源码来看看Struts2是如何保证拦截器、Action与Result三者之间的执行顺序的。以前我曾经提到,ActionInvocation是Struts2中的调度器,因此事实上,这些代码的调度执行,是在ActionInvocation的实现类中完成的,这里,我抽取了DefaultActionInvocation中的invoke()方法,它将向咱们展现一切。

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);  
    }  
}  

 从源码中,咱们能够看到Action层的4个不一样的层次,在这个方法中都有体现,他们分别是:拦截器(Interceptor)、Action、PreResultListener和Result。在这个方法中,保证了这些层次的有序调用和执行。由此咱们也能够看出Struts2在Action层次设计上的众多考虑,每一个层次都具有了高度的扩展性和插入点,使得程序员能够在任何喜欢的层次加入本身的实现机制改变Action的行为。
在这里,须要特别强调的,是其中拦截器部分的执行调用:

resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this); 

原来在intercept()方法又对ActionInvocation的invoke()方法进行递归调用,ActionInvocation循环嵌套在intercept()中,一直到语句result = invocation.invoke()执行结束。这样,Interceptor又会按照刚开始执行的逆向顺序依次执行结束。一个有序链表,经过递归调用,变成了一个堆栈执行过程,将一段有序执行的代码变成了2段执行顺序彻底相反的代码过程,从而巧妙地实现了AOP。这也就成为了Struts2的Action层的AOP基础。 

拦截器和过滤器之间有不少相同之处,可是二者之间存在根本的差异。其主要区别为如下几点:
1)拦截器是基于JAVA反射机制的,而过滤器是基于函数回调的。
2)过滤器依赖于Servlet容器,而拦截器不依赖于Servlet容器
3)拦截器只能对Action请求起做用,而过滤器能够对几乎全部的请求起做用。
4)拦截器能够访问Action上下文、值栈里的对象,而过滤器不能
5)在Action的生命周期中,拦截器能够屡次被调用,而过滤器只能在容器初始化时被调用一次。

相关文章
相关标签/搜索