在上一篇中介绍了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; } else return null; } catch (Exception e) { } } return invocation.invoke(); } }
以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索action类的问题
, action
, interceptor
, 方法
, 拦截器
, 拦截器中的方法
, struts2拦截器
, invoke
, 过滤器怎么调用action
, 拦截器aspnetsetmvcstring
, jerseyspring拦截器
, Struts 拦截器
, 一个
http拦截器
,以便于您获取更多的相关知识。