Struts2使用自定义拦截器
虽然Struts2框架提供了许多拦截器,这些内建的拦截器实现了Struts2的大部分功能,因此,大部分Web应用的通用功能,都可以通过直接使用这些拦截器来完成。但还有一些系统逻辑相关的通用功能,则可以通过自定义拦截器来实现。值得称道的是,Struts2的拦截器系统是如此的简单,易用。
实现拦截器类
如果用户要开发自己的拦截器类,应该实现com.opensymphony.xwork2.interceptor.Interceptor接口,该接口的类定义代码如下:
package com.opensymphony.xwork2.interceptor;import com.opensymphony.xwork2.ActionInvocation;import java.io.Serializable;public abstract interface Interceptor implements Serializable{ //销毁该拦截器之前的回调方法 public abstract void destroy(); //初始化该拦截器的回调方法 public abstract void init(); //拦截器实现拦截的逻辑方法 public abstract String intercept(ActionInvocation paramActionInvocation) throws Exception;}通过上面的接口可以看出,该接口里包含了三个方法:package com.opensymphony.xwork2.interceptor;import com.opensymphony.xwork2.ActionInvocation;public abstract class AbstractInterceptor implements Interceptor{ public void init() { } public void destroy() { } public abstract String intercept(ActionInvocation paramActionInvocation) throws Exception;}public class SimpleInterceptor extends AbstractInterceptor { // 简单拦截器的名字 private String name; // 为该简单拦截器设置名字的setter方法 public void setName(String name) { this.name = name; } // 拦截Action方法的intercept方法 public String intercept(ActionInvocation invocation) throws Exception { // 取得被拦截的Action实例 LoginAction action = (LoginAction) invocation.getAction(); // 打印 System.out.println(name + "拦截器的动作----------- 开始执行登录Action的时间为:" + new Date()); // 取得开始执行Action的时间 long start = System.currentTimeMillis(); // 执行该拦截器的后一个拦截器,或者直接指定Action的execute方法 String result = invocation.invoke(); System.out.println(name + " 拦截器的动作----------- 执行完登录Action的时间为: " + new Date()); // 取得执行完的事件 long end = System.currentTimeMillis(); System.out.println(name + "拦截器的动作----------- 执行完该Action的时间为:" + (end - start) + "毫秒"); return result; }} 上面的拦截器仅仅在被拦截方法之前,打印出开始执行Action的时间,并记录开始执行Action的时刻;执行被拦截Action的execute方法之后,再次打印出当前时间,并输出执行Action的时长。