西北旺附近男科医院:Struts2温习(6)--拦截器(Inteceptor)的使用 - 入则孝、出则悌、谨而...

来源:百度文库 编辑:九乡新闻网 时间:2024/05/08 19:35:25
的使用文章分类:Java编程

 

Interceptor(以下译为拦截器)是Struts 2的一个强有力的工具,有许多功能(feature)都是构建于它之上,如国际化、转换器,校验等。


什么是拦截器

拦截器,在AOP(Aspect-Oriented Programming)中用于在某个方法或字段被访问之前,进行拦截然后在之前或之后加入某些操作。拦截是AOP的一种实现策略。

在Webwork的中文文档的解释为——拦截器是动态拦截Action调用的对象。它提供了一种机制可以使开发者可以定义在一个action执行的前后执行的代码,也可以在一个action执行前阻止其执行。同时也是提供了一种可以提取action中可重用的部分的方式。

谈到拦截器,还有一个词大家应该知道——拦截器链(Interceptor Chain,在Struts 2中称为拦截器栈Interceptor Stack)。拦截器链就是将拦截器按一定的顺序联结成一条链。在访问被拦截的方法或字段时,拦截器链中的拦截器就会按其之前定义的顺序被调用。


实现原理

Struts 2的拦截器实现相对简单。当请求到达Struts 2的ServletDispatcher时,Struts 2会查找配置文件,并根据其配置实例化相对的拦截器对象,然后串成一个列表(list),最后一个一个地调用列表中的拦截器,如下图所示。

 



 

 

已有的拦截器

Struts 2已经为您提供丰富多样的,功能齐全的拦截器实现。大家可以到struts2-core-2.1.8.1.jar包的struts-default.xml查看关于默认的拦截器与拦截器链的配置。


 

以下部分就是从struts-default.xml文件摘取的内容:

 

 

Xml代码  
  1.  style="FONT-SIZE: large">< interceptor name ="alias" class ="com.opensymphony.xwork2.interceptor.AliasInterceptor" />    
  2. < interceptor name ="autowiring" class ="com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor" />    
  3. < interceptor name ="chain" class ="com.opensymphony.xwork2.interceptor.ChainingInterceptor" />    
  4. < interceptor name ="conversionError" class ="org.apache.struts2.interceptor.StrutsConversionErrorInterceptor" />    
  5. < interceptor name ="createSession" class ="org.apache.struts2.interceptor.CreateSessionInterceptor" />    
  6. < interceptor name ="debugging" class ="org.apache.struts2.interceptor.debugging.DebuggingInterceptor" />    
  7. < interceptor name ="external-ref" class ="com.opensymphony.xwork2.interceptor.ExternalReferencesInterceptor" />    
  8. < interceptor name ="execAndWait" class ="org.apache.struts2.interceptor.ExecuteAndWaitInterceptor" />    
  9. < interceptor name ="exception" class ="com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor" />    
  10. < interceptor name ="fileUpload" class ="org.apache.struts2.interceptor.FileUploadInterceptor" />    
  11. < interceptor name ="i18n" class ="com.opensymphony.xwork2.interceptor.I18nInterceptor" />    
  12. < interceptor name ="logger" class ="com.opensymphony.xwork2.interceptor.LoggingInterceptor" />    
  13. < interceptor name ="model-driven" class ="com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor" />    
  14. < interceptor name ="scoped-model-driven" class ="com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor" />    
  15. < interceptor name ="params" class ="com.opensymphony.xwork2.interceptor.ParametersInterceptor" />    
  16. < interceptor name ="prepare" class ="com.opensymphony.xwork2.interceptor.PrepareInterceptor" />    
  17. < interceptor name ="static-params" class ="com.opensymphony.xwork2.interceptor.StaticParametersInterceptor" />    
  18. < interceptor name ="scope" class ="org.apache.struts2.interceptor.ScopeInterceptor" />    
  19. < interceptor name ="servlet-config" class ="org.apache.struts2.interceptor.ServletConfigInterceptor" />    
  20. < interceptor name ="sessionAutowiring" class ="org.apache.struts2.spring.interceptor.SessionContextAutowiringInterceptor" />    
  21. < interceptor name ="timer" class ="com.opensymphony.xwork2.interceptor.TimerInterceptor" />    
  22. < interceptor name ="token" class ="org.apache.struts2.interceptor.TokenInterceptor" />    
  23. < interceptor name ="token-session" class ="org.apache.struts2.interceptor.TokenSessionStoreInterceptor" />    
  24. < interceptor name ="validation" class ="com.opensymphony.xwork2.validator.ValidationInterceptor" />    
  25. < interceptor name ="workflow" class ="com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor" />    
  26. < interceptor name ="store" class ="org.apache.struts2.interceptor.MessageStoreInterceptor" />    
  27. < interceptor name ="checkbox" class ="org.apache.struts2.interceptor.CheckboxInterceptor" />    
  28. < interceptor name ="profiling" class ="org.apache.struts2.interceptor.ProfilingActivationInterceptor" />   

 在struts-default.xml中已经配置了以上的拦截器。如果您想要使用上述拦截器,只需要在应用程序struts.xml文件中通过“”将struts-default.xml文件包含进来,并继承其中的struts-default包(package),最后在定义Action时,使用“”引用拦截器或拦截器栈(interceptor stack)。一旦您继承了struts-default包(package),所有Action都会调用拦截器栈 ——defaultStack。当然,在Action配置中加入“”可以覆盖defaultStack。

 

下面是关于拦截器timer使用的例子。首先,新建Action类tuotrial/TimerInterceptorAction.java,内容如下:

 

Java代码  
  1. "FONT-SIZE: large">package tutorial;   
  2.   
  3.  import com.opensymphony.xwork2.ActionSupport;   
  4.   
  5.  public class TimerInterceptorAction extends ActionSupport  {   
  6.     @Override  
  7.      public String execute()  {   
  8.          try  {   
  9.              // 模拟耗时的操作    
  10.             Thread.sleep( 500 );   
  11.         } catch (Exception e)  {   
  12.             e.printStackTrace();   
  13.         }    
  14.          return SUCCESS;   
  15.     }    
  16. }   

 

 配置Action,名为Timer,配置文件如下:

 

Java代码  
  1. "FONT-SIZE: large">
  2.         "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
  3.         "http://struts.apache.org/dtds/struts-2.0.dtd" >    
  4. < struts >    
  5.     < include file ="struts-default.xml" />       
  6.     < package name ="InterceptorDemo" extends ="struts-default" >    
  7.         < action name ="Timer" class ="tutorial.TimerInterceptorAction" >    
  8.             < interceptor-ref name ="timer" />    
  9.             < result > /Timer.jsp     
  10.             
  11.     package >    
  12.    

 

 

 

至于Timer.jsp可以随意写些什么到里面。发布运行应用程序,在浏览器的地址栏键入http://localhost:8080/Struts2_Interceptor/Timer.action,在出现Timer.jsp页面后,查看服务器的后台输出。

 


 

Java代码  
  1. "FONT-SIZE: large">信息: Executed action [ //Timer!execute ] took 2859 ms.   

 

 

 

在您的环境中执行Timer!execute的耗时,可能上述的时间有些不同,这取决于您PC的性能。但是无论如何,2859 ms与500 ms还是相差太远了。这是什么原因呢?其实原因是第一次加载Timer时,需要进行一定的初始工作。当你重新请求Timer.action时,以上输出会变为:

 

Java代码  
  1. "FONT-SIZE: large">信息: Executed action [ //Timer!execute ] took 500 ms.   

 

 OK,这正是我们期待的结果。上述例子演示了拦截器timer的用途——用于显示执行某个action方法的耗时,在我们做一个粗略的性能调试时,这相当有用。

 


 


自定义拦截器

所有的Struts 2的拦截器都直接或间接实现接口

 

Java代码  
  1. "FONT-SIZE: large">package com.javacrazyer.web.action;   
  2.   
  3. import com.opensymphony.xwork2.ActionInvocation;   
  4. import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;   
  5.   
  6. public class MyMethodInterceptor extends MethodFilterInterceptor {   
  7.   
  8.     /* (non-Javadoc)  
  9.      * @see com.opensymphony.xwork2.interceptor.MethodFilterInterceptor#doIntercept(com.opensymphony.xwork2.ActionInvocation)  
  10.      */  
  11.     @Override  
  12.     protected String doIntercept(ActionInvocation arg0) throws Exception {   
  13.         // TODO Auto-generated method stub   
  14.         return null;   
  15.     }   
  16.   
  17. }  

 MyInterceptor.java

 

Java代码  
  1. "FONT-SIZE: large">package com.javacrazyer.web.action;   
  2.   
  3. import com.opensymphony.xwork2.ActionInvocation;   
  4. import com.opensymphony.xwork2.interceptor.AbstractInterceptor;   
  5.   
  6.   
  7. @SuppressWarnings("serial")   
  8. public class MyInterceptor extends AbstractInterceptor {   
  9.   
  10.   
  11.     @Override  
  12.     public String intercept(ActionInvocation invocation) throws Exception {   
  13.         String result = null;   
  14.            
  15.           // invocation.invoke()之前的代码,将会在Action之前被依次执行   
  16.           String actionName = invocation.getAction().getClass().getName();   
  17.           // 获取此次调用的Action的方法名   
  18.           String method = invocation.getProxy().getMethod();   
  19.           System.out.println("开始执行"+actionName+"的"+method+"方法");   
  20.              
  21.           //Object obj = invocation.getInvocationContext().getSession().get("currAccount");   
  22.         //if(obj == null){   
  23.         //  return "input";   
  24.         //}else{   
  25.             result = invocation.invoke();  //调用下一个资源   
  26.         //}   
  27.           // invocation.invoke()之后的代码,将会在Action之后被逆序执行   
  28.           System.out.println("执行"+actionName+"的"+method+"方法完毕");   
  29.            
  30.         return result;   
  31.            
  32.     }   
  33.   
  34. }   
  35.   

 

 

src/struts.xml

 

Java代码  
  1. "FONT-SIZE: large">"1.0" encoding="UTF-8" ?>   
  2.     "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"  
  3.     "http://struts.apache.org/dtds/struts-2.1.7.dtd">   
  4.   
  5.   
  6.        
  7.     "struts.i18n.encoding" value="UTF-8"/>   
  8.        
  9.     "struts.action.extension" value="action,do,go,xkk"/>   
  10.        
  11.     "struts.configuration.xml.reload" value="true"/>   
  12.        
  13.     "struts.devMode" value="false"/>   
  14.        
  15.     "struts.serve.static.browserCache" value="false" />   
  16.        
  17.     "struts.ognl.allowStaticMethodAccess" value="true"/>   
  18.        
  19.        
  20.        
  21.     "struts.enable.DynamicMethodInvocation" value="false"/>   
  22.        
  23.        
  24.        
  25.     <package name="my" extends="struts-default" namespace="/">   
  26.            
  27.                
  28.             "myInterceptor" class="com.javacrazyer.web.action.MyInterceptor"/>   
  29.                
  30.             "myStack">   
  31.                 "defaultStack"/>   
  32.                 "myInterceptor"/>   
  33.                
  34.            
  35.        
  36.         "ognl" class="com.javacrazyer.web.action.OGNLAction">   
  37.             /ognl_info.jsp   
  38.                
  39.             "defaultStack"/>   
  40.             "myInterceptor"/>   
  41.            
  42.     package>   
  43.        
  44.