一般情况下,为Action配置了拦截器,拦截器会拦截Action中的所有方法,但有时只需要拦截其中的某些方法。这是就需要struts的拦截器方法过滤特性。自定义拦截器需继承MethodFilterInterceptor抽象类。
package com.demo1.interceptor;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
public class Methodfilterinterceptor extends MethodFilterInterceptor{
public String doIntercept(ActionInvocation ai) throws Exception{
System.out.println("拦截器方法过滤实现");
return ai.invoke();
}
}
因为MethodFilterInterceptor类提供了如下两个方法。
设置不需过滤的方法:
public void setExcludeMethods(String excludeMethods) {
this.excludeMethods = TextParseUtil
.commaDelimitedStringToSet(excludeMethods);
}
设置过滤的方法
public void setIncludeMethods(String includeMethods) {
this.includeMethods = TextParseUtil
.commaDelimitedStringToSet(includeMethods);
}
这样就可以在配置文件中设置参数
<interceptors>
<interceptor name="methodfilterInterceptor" class="com.demo1.interceptor.Methodfilterinterceptor"/>
</interceptors>
<action name="loginAction" class="com.demo1.action.LoginAction" method="checkLogin">
<result name="success">/index.jsp</result>
<result name="login">/login.jsp</result>
<interceptor-ref name="defaultStack"/>
<interceptor-ref name="methodfilterInterceptor">
<param name="excludeMethods">checkLogin</param><!--此方法不需顾虑,多个方法以半角逗号隔开,-->
<!--<param name="includeMethods">checkLogin<param> 方法需要过滤,此语句也可以不用配置-->
</interceptor-ref>
</action>
如果一个方法既配置在 excludeMethods又被配置在 includeMethods中,拦截器会以includeMethods优先即拦截此方法。