自定义拦截器,一般用到的不多,如果用到,估计也就是你的设计哪里出了bug吧,但是Struts2既然有这个知识点,应该还是要学一下的。
1.首先写一个类,实现Interceptor这个接口。在intercept()方法中获取action被拦截的时间。
package com.seven.interceptor;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
/**
* 自定义拦截器
* @author Administrator
*
*/
public class MyInterceptor implements Interceptor{
public void destroy() {}
public void init() {}
public String intercept(ActionInvocation invocation) throws Exception {
long start = System.currentTimeMillis();
String r = invocation.invoke();
long end=System.currentTimeMillis();
System.out.println("action time = "+(end-start));
return r;
}
}
2.在struts.xml配置文件中做如下配置
<package name="test" extends="struts-default">
<interceptors>
<interceptor name="my" class="com.seven.interceptor.MyInterceptor"></interceptor>
</interceptors>
<action name="test" class="com.seven.action.TestAction">
<interceptor-ref name="my"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
<result>/Test.jsp</result>
</action>
</package>
这里defaultStack是Struts2的默认拦截器,在自定义拦截器之后,还要默认的拦截器。因为如果不加,就只有自己定义的拦截器。如果两个拦截器都不写,系统会自动调用默认的拦截器。