拦截器拦截的是action中的每一个业务方法,而当我们只想让拦截器拦截特定方法,以提高效率时,使用拦截器就不是那么适合了,这时,我们可以使用方法拦截器。
1.定义方法拦截器
方法拦截器要继承 MethodFilterInterceptor 类,实现 doIntercept 方法,该方法体就是实现特定的拦截业务
public class MethodInterceptor extends MethodFilterInterceptor {
@Override
protected String doIntercept(ActionInvocation actionInvocation) throws Exception {
// 要实现的拦截功能
System.out.println("method interceptor is running");
//调用下个拦截器,没有下个拦截器,就调用业务方法
actionInvocation.invoke();
return null;
}
}
2.配置拦截器
首先要注册拦截器
<interceptors>
<interceptor name="methodInterceptor" class="com.interceptor.MethodInterceptor"></interceptor>
</interceptors>
接着引用拦截器
<interceptor-ref name="methodInterceptor">
<!-- 要拦截的特定业务方法 -->
<param name="includeMethods">login,check</param>
<!-- 不拦截的特定业务方法 >
<param name="excludeMethods"></param -->
</interceptor-ref>
完毕
我的整体配置如下
<package name="default" namespace="/" extends="struts-default">
<interceptors>
<interceptor name="methodInterceptor" class="com.interceptor.MethodInterceptor"></interceptor>
</interceptors>
<global-allowed-methods>check,login,look</global-allowed-methods>
<!-- 在action中使用自定义拦截器 -->
<action name="*" class="com.action.LoginAction" method="{1}">
<result>/index.jsp</result>
<result name="check">/index.jsp</result>
<result name="look">/index.jsp</result>
<interceptor-ref name="methodInterceptor">
<!-- 要拦截的特定业务方法 -->
<param name="includeMethods">login,check</param>
<!-- 不拦截的特定业务方法 >
<param name="excludeMethods"></param -->
</interceptor-ref>
</action>
</package>
这样就只会拦截login与check业务方法了