struts2的拦截器(4)-通过继承AbstractInterceptor抽象类定义自己的拦截器

发布时间:2025-12-09 14:03:10 浏览次数:6

抽象类AbstractInterceptor实现了Interceptor接口,提供了init和destroy方法的空实现。如果我们的拦截器不需要打开资源,则可以无需实现这两个方法。可见通过继承AbstractInterceptor抽象类来实现自定义拦截器会更简单。

将上篇文章中的SimpleInterceptor.java 改为如下实现,其余所有代码一律不变:

public class SimpleInterceptor extends AbstractInterceptor {private String name;public void setName(String name) {this.name = name;}@Overridepublic String intercept(ActionInvocation invocation) throws Exception {LoginAction loginaction=(LoginAction)invocation.getAction();System.out.println(name+"拦截器的动作------"+"开始执行登录Action的时间为:"+new Date());long start=System.currentTimeMillis();String result=invocation.invoke();  //要理解这行代码System.out.println(name+"拦截器的动作------"+"执行完登录Action的时间为:"+new Date());long end=System.currentTimeMillis();System.out.println("执行完该Action耗时:"+(end-start)+"毫秒");return result;   //要理解这行代码}}

struts2拦截器的功能非常强大,它既可以在Action的execute方法之前插入执行代码,也可以在execute方法之后插入执行代码,这种方式的实质就是
AOP(面向切面编程)的思想。

需要做网站?需要网络推广?欢迎咨询客户经理 13272073477