西北旺附近男科医院:Struts2温习(6)--拦截器(Inteceptor)的使用 - 入则孝、出则悌、谨而...
来源:百度文库 编辑:九乡新闻网 时间:2024/05/08 19:35:25
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代码
- style="FONT-SIZE: large">< interceptor name ="alias" class ="com.opensymphony.xwork2.interceptor.AliasInterceptor" />
- < interceptor name ="autowiring" class ="com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor" />
- < interceptor name ="chain" class ="com.opensymphony.xwork2.interceptor.ChainingInterceptor" />
- < interceptor name ="conversionError" class ="org.apache.struts2.interceptor.StrutsConversionErrorInterceptor" />
- < interceptor name ="createSession" class ="org.apache.struts2.interceptor.CreateSessionInterceptor" />
- < interceptor name ="debugging" class ="org.apache.struts2.interceptor.debugging.DebuggingInterceptor" />
- < interceptor name ="external-ref" class ="com.opensymphony.xwork2.interceptor.ExternalReferencesInterceptor" />
- < interceptor name ="execAndWait" class ="org.apache.struts2.interceptor.ExecuteAndWaitInterceptor" />
- < interceptor name ="exception" class ="com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor" />
- < interceptor name ="fileUpload" class ="org.apache.struts2.interceptor.FileUploadInterceptor" />
- < interceptor name ="i18n" class ="com.opensymphony.xwork2.interceptor.I18nInterceptor" />
- < interceptor name ="logger" class ="com.opensymphony.xwork2.interceptor.LoggingInterceptor" />
- < interceptor name ="model-driven" class ="com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor" />
- < interceptor name ="scoped-model-driven" class ="com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor" />
- < interceptor name ="params" class ="com.opensymphony.xwork2.interceptor.ParametersInterceptor" />
- < interceptor name ="prepare" class ="com.opensymphony.xwork2.interceptor.PrepareInterceptor" />
- < interceptor name ="static-params" class ="com.opensymphony.xwork2.interceptor.StaticParametersInterceptor" />
- < interceptor name ="scope" class ="org.apache.struts2.interceptor.ScopeInterceptor" />
- < interceptor name ="servlet-config" class ="org.apache.struts2.interceptor.ServletConfigInterceptor" />
- < interceptor name ="sessionAutowiring" class ="org.apache.struts2.spring.interceptor.SessionContextAutowiringInterceptor" />
- < interceptor name ="timer" class ="com.opensymphony.xwork2.interceptor.TimerInterceptor" />
- < interceptor name ="token" class ="org.apache.struts2.interceptor.TokenInterceptor" />
- < interceptor name ="token-session" class ="org.apache.struts2.interceptor.TokenSessionStoreInterceptor" />
- < interceptor name ="validation" class ="com.opensymphony.xwork2.validator.ValidationInterceptor" />
- < interceptor name ="workflow" class ="com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor" />
- < interceptor name ="store" class ="org.apache.struts2.interceptor.MessageStoreInterceptor" />
- < interceptor name ="checkbox" class ="org.apache.struts2.interceptor.CheckboxInterceptor" />
- < interceptor name ="profiling" class ="org.apache.struts2.interceptor.ProfilingActivationInterceptor" />
< interceptor name ="alias" class ="com.opensymphony.xwork2.interceptor.AliasInterceptor" />< interceptor name ="autowiring" class ="com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor" />< interceptor name ="chain" class ="com.opensymphony.xwork2.interceptor.ChainingInterceptor" />< interceptor name ="conversionError" class ="org.apache.struts2.interceptor.StrutsConversionErrorInterceptor" />< interceptor name ="createSession" class ="org.apache.struts2.interceptor.CreateSessionInterceptor" />< interceptor name ="debugging" class ="org.apache.struts2.interceptor.debugging.DebuggingInterceptor" />< interceptor name ="external-ref" class ="com.opensymphony.xwork2.interceptor.ExternalReferencesInterceptor" />< interceptor name ="execAndWait" class ="org.apache.struts2.interceptor.ExecuteAndWaitInterceptor" />< interceptor name ="exception" class ="com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor" />< interceptor name ="fileUpload" class ="org.apache.struts2.interceptor.FileUploadInterceptor" />< interceptor name ="i18n" class ="com.opensymphony.xwork2.interceptor.I18nInterceptor" />< interceptor name ="logger" class ="com.opensymphony.xwork2.interceptor.LoggingInterceptor" />< interceptor name ="model-driven" class ="com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor" />< interceptor name ="scoped-model-driven" class ="com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor" />< interceptor name ="params" class ="com.opensymphony.xwork2.interceptor.ParametersInterceptor" />< interceptor name ="prepare" class ="com.opensymphony.xwork2.interceptor.PrepareInterceptor" />< interceptor name ="static-params" class ="com.opensymphony.xwork2.interceptor.StaticParametersInterceptor" />< interceptor name ="scope" class ="org.apache.struts2.interceptor.ScopeInterceptor" />< interceptor name ="servlet-config" class ="org.apache.struts2.interceptor.ServletConfigInterceptor" />< interceptor name ="sessionAutowiring" class ="org.apache.struts2.spring.interceptor.SessionContextAutowiringInterceptor" />< interceptor name ="timer" class ="com.opensymphony.xwork2.interceptor.TimerInterceptor" />< interceptor name ="token" class ="org.apache.struts2.interceptor.TokenInterceptor" />< interceptor name ="token-session" class ="org.apache.struts2.interceptor.TokenSessionStoreInterceptor" />< interceptor name ="validation" class ="com.opensymphony.xwork2.validator.ValidationInterceptor" />< interceptor name ="workflow" class ="com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor" />< interceptor name ="store" class ="org.apache.struts2.interceptor.MessageStoreInterceptor" />< interceptor name ="checkbox" class ="org.apache.struts2.interceptor.CheckboxInterceptor" />< interceptor name ="profiling" class ="org.apache.struts2.interceptor.ProfilingActivationInterceptor" />
在struts-default.xml中已经配置了以上的拦截器。如果您想要使用上述拦截器,只需要在应用程序struts.xml文件中通过“
下面是关于拦截器timer使用的例子。首先,新建Action类tuotrial/TimerInterceptorAction.java,内容如下:
Java代码
- "FONT-SIZE: large">package tutorial;
- import com.opensymphony.xwork2.ActionSupport;
- public class TimerInterceptorAction extends ActionSupport {
- @Override
- public String execute() {
- try {
- // 模拟耗时的操作
- Thread.sleep( 500 );
- } catch (Exception e) {
- e.printStackTrace();
- }
- return SUCCESS;
- }
- }
package tutorial;import com.opensymphony.xwork2.ActionSupport;public class TimerInterceptorAction extends ActionSupport {@Overridepublic String execute() {try {// 模拟耗时的操作Thread.sleep( 500 );} catch (Exception e) {e.printStackTrace();}return SUCCESS;}}
配置Action,名为Timer,配置文件如下:
Java代码
- "FONT-SIZE: large">
- "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
- "http://struts.apache.org/dtds/struts-2.0.dtd" >
- < struts >
- < include file ="struts-default.xml" />
- < package name ="InterceptorDemo" extends ="struts-default" >
- < action name ="Timer" class ="tutorial.TimerInterceptorAction" >
- < interceptor-ref name ="timer" />
- < result > /Timer.jsp result >
- action >
- package >
- struts >
< struts >< include file ="struts-default.xml" />< package name ="InterceptorDemo" extends ="struts-default" >< action name ="Timer" class ="tutorial.TimerInterceptorAction" >< interceptor-ref name ="timer" />< result > /Timer.jsp result > action > package > struts >
至于Timer.jsp可以随意写些什么到里面。发布运行应用程序,在浏览器的地址栏键入http://localhost:8080/Struts2_Interceptor/Timer.action,在出现Timer.jsp页面后,查看服务器的后台输出。
Java代码
- "FONT-SIZE: large">信息: Executed action [ //Timer!execute ] took 2859 ms.
信息: Executed action [ //Timer!execute ] took 2859 ms.
在您的环境中执行Timer!execute的耗时,可能上述的时间有些不同,这取决于您PC的性能。但是无论如何,2859 ms与500 ms还是相差太远了。这是什么原因呢?其实原因是第一次加载Timer时,需要进行一定的初始工作。当你重新请求Timer.action时,以上输出会变为:
Java代码
- "FONT-SIZE: large">信息: Executed action [ //Timer!execute ] took 500 ms.
信息: Executed action [ //Timer!execute ] took 500 ms.
OK,这正是我们期待的结果。上述例子演示了拦截器timer的用途——用于显示执行某个action方法的耗时,在我们做一个粗略的性能调试时,这相当有用。
自定义拦截器
所有的Struts 2的拦截器都直接或间接实现接口
Java代码
- "FONT-SIZE: large">package com.javacrazyer.web.action;
- import com.opensymphony.xwork2.ActionInvocation;
- import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
- public class MyMethodInterceptor extends MethodFilterInterceptor {
- /* (non-Javadoc)
- * @see com.opensymphony.xwork2.interceptor.MethodFilterInterceptor#doIntercept(com.opensymphony.xwork2.ActionInvocation)
- */
- @Override
- protected String doIntercept(ActionInvocation arg0) throws Exception {
- // TODO Auto-generated method stub
- return null;
- }
- }
package com.javacrazyer.web.action;import com.opensymphony.xwork2.ActionInvocation;import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;public class MyMethodInterceptor extends MethodFilterInterceptor {/* (non-Javadoc)* @see com.opensymphony.xwork2.interceptor.MethodFilterInterceptor#doIntercept(com.opensymphony.xwork2.ActionInvocation)*/@Overrideprotected String doIntercept(ActionInvocation arg0) throws Exception {// TODO Auto-generated method stubreturn null;}}
MyInterceptor.java
Java代码
- "FONT-SIZE: large">package com.javacrazyer.web.action;
- import com.opensymphony.xwork2.ActionInvocation;
- import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
- @SuppressWarnings("serial")
- public class MyInterceptor extends AbstractInterceptor {
- @Override
- public String intercept(ActionInvocation invocation) throws Exception {
- String result = null;
- // invocation.invoke()之前的代码,将会在Action之前被依次执行
- String actionName = invocation.getAction().getClass().getName();
- // 获取此次调用的Action的方法名
- String method = invocation.getProxy().getMethod();
- System.out.println("开始执行"+actionName+"的"+method+"方法");
- //Object obj = invocation.getInvocationContext().getSession().get("currAccount");
- //if(obj == null){
- // return "input";
- //}else{
- result = invocation.invoke(); //调用下一个资源
- //}
- // invocation.invoke()之后的代码,将会在Action之后被逆序执行
- System.out.println("执行"+actionName+"的"+method+"方法完毕");
- return result;
- }
- }
package com.javacrazyer.web.action;import com.opensymphony.xwork2.ActionInvocation;import com.opensymphony.xwork2.interceptor.AbstractInterceptor;@SuppressWarnings("serial")public class MyInterceptor extends AbstractInterceptor {@Overridepublic String intercept(ActionInvocation invocation) throws Exception {String result = null;// invocation.invoke()之前的代码,将会在Action之前被依次执行String actionName = invocation.getAction().getClass().getName();// 获取此次调用的Action的方法名String method = invocation.getProxy().getMethod();System.out.println("开始执行"+actionName+"的"+method+"方法");//Object obj = invocation.getInvocationContext().getSession().get("currAccount");//if(obj == null){//return "input";//}else{result = invocation.invoke(); //调用下一个资源//}// invocation.invoke()之后的代码,将会在Action之后被逆序执行System.out.println("执行"+actionName+"的"+method+"方法完毕");return result;}}
src/struts.xml
Java代码
- "FONT-SIZE: large">"1.0" encoding="UTF-8" ?>
- "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
- "http://struts.apache.org/dtds/struts-2.1.7.dtd">
-
"struts.i18n.encoding" value="UTF-8"/> -
"struts.action.extension" value="action,do,go,xkk"/> -
"struts.configuration.xml.reload" value="true"/> -
"struts.devMode" value="false"/> -
"struts.serve.static.browserCache" value="false" /> -
"struts.ognl.allowStaticMethodAccess" value="true"/> -
"struts.enable.DynamicMethodInvocation" value="false"/> - <package name="my" extends="struts-default" namespace="/">
-
-
"myInterceptor" class="com.javacrazyer.web.action.MyInterceptor"/> -
"myStack"> -
"defaultStack"/> -
"myInterceptor"/> -
"ognl" class="com.javacrazyer.web.action.OGNLAction"> -
/ognl_info.jsp -
"defaultStack"/> -
"myInterceptor"/> - package>