Stuts2拦截器
在我们的web.xml中,我们配置了一个过滤器,实现将所有请求交付StrutsPrepareAndExecuteFilter类。一旦接受到任意action的请求,该类会创建和初始化一个ActionProxy实例,它代理了具体的action,在其中我们可以添加任意拦截器在execute方法执行之前和之后做一些额外的操作,最终会调用该action实例的execute方法,为用户返回视图结果字符串,然后系统会根据该视图结果字符串调取相应的视图页面。下图是拦截器和action之间的关系:
来源:https://www.cnblogs.com/yangming1996/p/6902752.html
实现拦截器的步骤:
- 创建一个自定义拦截器(实现Interceptor接口或者继承AbstractInterceptor类)
- 编写拦截器
- 使用接口:实现init、destroy、intercept(ActionInvocation invocation)三个方法
- 继承:重写父类intercept(ActionInvocation invocation)方法
3在struts.xml中配置拦截器,并且在Action中引用
举个列子(写一个计算执行一个Action所耗时间的拦截器)
- 创建一个自定义拦截器:
- 编写拦截器,以使用接口为例
public String intercept(ActionInvocation invocation) throws Exception { long start=System.currentTimeMillis(); //返回结果集 String result=invocation.invoke(); long stop=System.currentTimeMillis(); System.out.println("Action执行完成所耗时间:"+(stop-start)+"ms"); return result; } public void init() { } public void destroy() { } |
- 在struts.xml中配置拦截器,并且在Action中引用
<package name="runtimedemo" namespace="/" extends="struts-default"> <!-- interceptors里面可以配置多个拦截器/栈 --> <interceptors> <!-- 配置拦截器 --> <interceptor name="runtime" class="com.interceptor.RunTimeInterceptor"/> </interceptors>
<action name="run" class="com.action.RunTimeAction"> <result name="success">/index.jsp</result> <!-- 引用拦截器 --> <interceptor-ref name="runtime"/> </action> </package> |
- JSP页面
<body> <a href="run.action">执行Action</a> </body> |
测试:
注意:如果使用了自定义拦截器那么默认的拦截器将会不起作用需要我们手动引用。
证明:在action中传以个参数并且在Action中尝试获取该参数。
public class RunTimeAction { private String name; public String execute() { System.out.println("execute执行"); System.out.println("name=="+name ); return "success"; } } public void setName(String name) { this.name = name; } |
测试
传了一个参数但是没有获取到的原因就是默认拦截器没有起作用。
PS:拦截器和默认拦截器在struts-default.xml中可以找到
默认拦截器
<default-interceptor-ref name="defaultStack"/> |
所有拦截器在struts-default.xml里面的</interceptors>标签里面
根据struts-default.xml所以我们只需要在Action里面引用默认拦截器就好了
<action name="run" class="com.action.RunTimeAction"> <result name="success">/index.jsp</result> <!-- 引用拦截器 --> <interceptor-ref name="runtime"/> <!-- 引用默认拦截器 --> <interceptor-ref name="defaultStack"/> </action> |
再来测试结果就正常了
拦截器的详细配置
以本例的struts.xml里面的配置为例
- 多个拦截器组成拦截器栈
<interceptors> <!-- 配置拦截器栈,拦截器栈里面也可以引用多个拦截器栈 --> <interceptor name="runtime" class="com.interceptor.RunTimeInterceptor"/> <interceptor-stack name="myInterceptors"> <interceptor-ref name="runtime"/> <interceptor-ref name="defaultStack"/> </interceptor-stack> </interceptors> <action name="run" class="com.action.RunTimeAction"> <result name="success">/index.jsp</result> <!-- 引用自定义的拦截器栈 --> <interceptor-ref name="myInterceptors"/> </action> |
- 定义默认使用的拦截器/栈
<!-- 默认的拦截器栈 --> <default-interceptor-ref name="myInterceptors"/> |