Struts2教程9:实现自已的拦截器2011-07-03 BlogJava nokiaguy在上一篇中介绍了Struts2拦截器的原理,在这一篇中我们将学习一下如何编写自己的拦截器。一、拦截器的实现实现一个拦截器非常简单。实际上,一个拦截器就是一个普通的类,只是这个类必须实现com.opensymphony.xwork2.interceptor.Interceptor接口。Interceptor接口有如下三个方法:
public interface Interceptor extends Serializable {void destroy();void init();String intercept(ActionInvocation invocation) throws Exception;}其中init和destroy方法只在拦截器加载和释放(都由Struts2自身处理)时执行一次。而intercept方法在每次访问动作时都会被调用。Struts2在调用拦截器时,每个拦截器类只有一个对象实例,而所有引用这个拦截器的动作都共享这一个拦截器类的对象实例,因此,在实现Interceptor接口的类中如果使用类变量,要注意同步问题。下面我们来实现一个简单的拦截器,这个拦截器通过请求参数action指定一个拦截器类中的方法,并调用这个方法(我们可以使用这个拦截器对某一特定的动作进行预处理)。如果方法不存在,或是action参数不存在,则继续执行下面的代码。如下面的URL:http://localhost:8080/struts2/test/interceptor.action?action=test访问上面的url后,拦截器会就会调用拦截器中的test方法,如果这个方法不存在,则调用invocation.invoke方法,invoke方法和Servlet过滤器中调用FilterChain.doFilter方法类似,如果在当前拦截器后面还有其他的拦截器,则invoke方法就是调用后面拦截器的intercept方法,否则,invoke会调用Action类的execute方法(或其他的执行方法)。下面我们先来实现一个拦截器的父类ActionInterceptor。这个类主要实现了根据action参数值来调用方法的功能,代码如下:
package interceptor;import com.opensymphony.xwork2.ActionInvocation;import com.opensymphony.xwork2.interceptor.Interceptor;import javax.servlet.http.*;import org.apache.struts2.*;public class ActionInterceptor implements Interceptor{protected final String INVOKE = "##invoke"; public void destroy(){System.out.println("destroy");}public void init(){System.out.println("init");}public String intercept(ActionInvocation invocation) throws Exception{HttpServletRequest request = ServletActionContext.getRequest();String action = request.getParameter("action");System.out.println(this.hashCode());if (action != null){try{java.lang.reflect.Method method = this.getClass().getMethod(action);String result = (String)method.invoke(this);if(result != null){if(!result.equals(INVOKE))return result;}elsereturn null;}catch (Exception e){}}return invocation.invoke();}}