1、创建一个继承自AbstractInterceptor类
2、实现intercept方法
3、注册拦截器
<interceptors> <interceptor name="mytimer" class="com.interceptor.TimerInterceptor"/> </interceptors>
4、引用拦截器
<action name="timer" class="com.action.TimerAction"> <result>/index.jsp</result> <!--引用拦截器--> <interceptor-ref name="mytimer"/> </action>
如何创建拦截器
1.定义拦截器 1.1.创建一个拦截器类继承自AbstractInterceptor类 1.2.实现intercept方法 eg: public String intercept(ActionInvocation invocation) throws Exception { //1.执行action之前 long start=System.currentTimeMillis(); //2.执行下一个拦截器,如果是最后一个拦截器,则执行目标action String result=invocation.invoke(); //3.执行action之后 long end=System.currentTimeMillis(); //4.花费的时间 long time=end-start; System.out.println("执行花费的时间: "+time+" ms"); return result; } 2.配置拦截器 <interceptors> <interceptor name="timeinterceptor" class="com.imooc.interceptor.TimerInterceptor"></interceptor> </interceptors> 3.引用拦截器 <interceptor-ref name="timeinterceptor"></interceptor-ref>
定义拦截器分为两大步:
1.创建一个继承自AbstractInterceptor的类
2.实现intercept方法,在这个方法中,实现拦截的操作。
(1)当执行Action时,会自动调用这个intercept方法
(2)在struts.xml中进行配置。首先注册拦截器,然后在相应的Action中进行引用拦截器
拦截器:Interceptor
拦截器的创建: 实现Interceptor接口(实现该接口的init、destory、interceptor方法,init、destory方法可以空实现) 或者继承AbstractInterceptor抽象类(该类已经空实现了init、destory方法,所以只需要实现interceptor方法即可) interceptor方法:
第一次拦截操作; 执行下一个拦截器,如果为最终拦截器,则执行Action的执行方法(invocation.invoke();,//invocation为interceptor方法的ActionInvocation参数名,invocation.invoke()返回一个string类型的返回值,该值等于action执行方法的返回值,可以使用变量result接受)
第二次拦截操作,return result;
拦截器配置:
注册拦截器 <package>标签下创建<interceptors>标签 <interceptors>标签内创建<interceptor>子标签,并给其name属性赋值
2、引用拦截器 <action>标签下使用<interceptor-ref>标签引用,<interceptor-ref>标签的name属性值对应拦截其的name