实际开发自然避免不了增加符合需求的拦截器,那么如何来开发呢?根据源码的结构分析,大概有两个步骤。
定义一个拦截器类
和自定义filter过滤器一样,自定义的拦截器类也要实现Interceptor接口,或者继承AbstractInterceptor抽象类。
要注意导入包的路径,是基于xwork2框架的包。
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
/**
* @className TestInterceptor
* @date 2021/4/24 13:13
* @description
**/
public class TestInterceptor implements Interceptor {
@Override
public void destroy() {}
@Override
public void init() {}
@Override
public String intercept(ActionInvocation actionInvocation) throws Exception {
return null;
}
}
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
/**
* @className InterceptorTest
* @date 2021/4/24 13:14
* @description
**/
public class InterceptorTest extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation actionInvocation) throws Exception {
return null;
}
}
在struts.xml在配置和使用
注意在引用自定义interceptor时还要加上默认的defaultStack
拦截器栈。
当然,拦截器的intercept()
方法要根据需要实现。
<package name="default" namespace="/" extends="struts-default">
<interceptors>
<interceptor name="interceptorTest" class="com.example.interceptor.InterceptorTest"></interceptor>
<interceptor name="testInterceptor" class="com.example.interceptor.TestInterceptor"></interceptor>
</interceptors>
<action name="test" class="com.example.action.TestAction">
<interceptor-ref name="interceptorTest"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
<result>/success.jsp</result>
</action>
</package>
注意
@Override
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("before invocation.invoke...");
//调用invoke()方法实现后续interceptor的回调
String result = invocation.invoke();
System.out.println("after invocation.invoke...");
return "success";
}
根据原理可知,完整拦截器栈所有的intercept()方法靠的就是ActionInvocation的回调,所以要加上String result = invocation.invoke();
。