struts2的默认prepare拦截器

来源:互联网 发布:暴漫官方淘宝店是哪个 编辑:程序博客网 时间:2024/06/03 22:49

在struts2的struts-default.xml中定义了一个name为prepare拦截器,实现类是com.opensymphony.xwork2.interceptor.PrepareInterceptor,它的作用是为实现了com.opensymphony.xwork2.Preparable接口的action调用相关方法。该拦截器有两个参数:alwaysInvokePrepare,firstCallPrepareDo,两者的类型都是boolean,默认值分别是true,false。

该拦截器的核心代码如下:

 

Java代码  收藏代码
  1. public String doIntercept(ActionInvocation invocation) throws Exception {  
  2.     Object action = invocation.getAction();  
  3.     if (action instanceof Preparable) {  
  4.         try {  
  5.             String[] prefixes;  
  6.             if (firstCallPrepareDo) {  
  7.                 prefixes = new String[] {ALT_PREPARE_PREFIX, PREPARE_PREFIX};  
  8.             } else {  
  9.                 prefixes = new String[] {PREPARE_PREFIX, ALT_PREPARE_PREFIX};  
  10.             }  
  11.             PrefixMethodInvocationUtil.invokePrefixMethod(invocation, prefixes);  
  12.         }  
  13.         catch (InvocationTargetException e) {  
  14.             /* 
  15.              * The invoked method threw an exception and reflection wrapped it 
  16.              * in an InvocationTargetException. 
  17.              * If possible re-throw the original exception so that normal 
  18.              * exception handling will take place. 
  19.              */  
  20.             Throwable cause = e.getCause();  
  21.             if (cause instanceof Exception) {  
  22.                 throw (Exception) cause;  
  23.             } else if(cause instanceof Error) {  
  24.                 throw (Error) cause;  
  25.             } else {  
  26.                 /* 
  27.                  * The cause is not an Exception or Error (must be Throwable) so 
  28.                  * just re-throw the wrapped exception. 
  29.                  */  
  30.                 throw e;  
  31.             }  
  32.         }  
  33.         if (alwaysInvokePrepare) {  
  34.             ((Preparable) action).prepare();  
  35.         }  
  36.     }  
  37.     return invocation.invoke();  
  38. }  

该代码的逻辑非常简单,如果action实现了com.opensymphony.xwork2.Preparable接口,则在调用setXXX和execute()方法之前调用系列方法。如果firstCallPrepareDo为true,则调用prepareDoXXX方法,否则调用prepareXXX方法(XXX为action对应的方法)。接下来查看alwaysInvokePrepare状态,如果其值为true则调用com.opensymphony.xwork2.Preparable接口的prepare方法。最后将action转交给下一个拦截器。

0 0
原创粉丝点击