在上一篇文章中,记录了拦截器的使用方式有2种。这次学习的内容便是使用继承abstractinterceptor类来实现拦截器的简单应用。
首先我们创建2个jsp页面:timestart.jsp
<body>
<a href="timer">点击此处开始计算Action时间</a>
</body>
timeend.jsp
<body>
action执行完毕<br>
</body>
然后我们来创建一个action:timeaction.java,我们等下通过拦截器来计算这个action的调用时间,所以我们在这个action里面写一个循环。
public class TimerAction extends ActionSupport {
@Override
public String execute() throws Exception {
for(int i=0;i<1000;i++){
System.out.println(i);
}
return SUCCESS;
}
}
在我们之前的xml文件里面配置这个action:
<action name="timer" class="com.imooc.action.TimerAction">
<result>timeend.jsp</result>
</action>
此时执行一下,可以看到是可以跳转到timeend.jsp的页面。这里就不传结果图了。
接下来制作一个拦截器,首先是继承abstractinterceptor类:TimeInterceptor.java
public class TimeInterceptor extends AbstractInterceptor {
@Override
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();
System.out.println("action执行的时间为:"+(end-start));
return result;
}
}
通过以上代码,写好了一个拦截器,下面需要把这个拦截器配置到xml里面:
<!--注册拦截器 -->
<interceptors>
<interceptor name="mytimer" class="com.imooc.interceptor.TimeInterceptor"></interceptor>
</interceptors>
<action name="timer" class="com.imooc.action.TimerAction">
<result>timeend.jsp</result>
<!--引用拦截器 -->
<interceptor-ref name="mytimer"></interceptor-ref>
</action>
以下是运行结果:
最后可以总结为,拦截器的使用需要2点:
一、继承abstractinterceptor类来创建自定义的拦截器
二、在xml里面配置相应的拦截器和调用。