一、实现Interceptor接口
public interface Interceptor extends Serializable{
public void init();
public void destroy();
public String intercept(ActionInvocation invocation)();
}
二、AbstractInterceptor继承类
重写intercept()方法
invocation.invoke();表示该方法执行完后执行Action的execute()方法或者执行下一个拦截器
invocation.getAction(); 可以将该法强制转换为Action的类类型
三、MethodFilterInterceptor继承类
重写doIntercept()方法
MethodFilerInterceptor实现方法过滤中用到的两个参数:
- execludeMethods
该参数指定拦截器拒绝拦截的方法列表,多个方法用“,”隔开,指定了这个参数,拦截器不会拦截指定列表中的方法,就是所谓的黑名单 - includeMethods
该参数指定拦截器需要拦截的方法列表,如果指定了参数,则指定的Action在执行前会被拦截,即白名单。
MethodFilerInterceptor实现类:
public class UserInterceptor extends MethodFilterInterceptor{
/**
* 进行拦截的方法
*/
protected String doIntercept(ActionInvocation invocation) throws Exception {
// 获取session对象
User user = (User) ServletActionContext.getRequest().getSession().getAttribute("existUser");
if(user == null){
// 说明,没有登录,后面就不会执行了
return "login";
}
return invocation.invoke();
}
}
struts.xml
<struts>
<package name="hadwin" namespace="/" extends="struts-default">
<!-- 配置拦截器 -->
<interceptors>
<interceptor name="UserInterceptor" class="com.hadwin.interceptor.UserInterceptor"/>
</interceptors>
<global-results>
<result name="login">/login.htm</result>
</global-results>
<!-- 配置用户的模块 -->
<action name="user_*" class="com.hadwin.action.UserAction" method="{1}">
<!-- <result name="login">/login.htm</result> -->
<result name="success">/index.htm</result>
<interceptor-ref name="UserInterceptor">
<!-- login方法不拦截,可以在这写也可以在interceptor定义处写都行 -->
<param name="excludeMethods">login</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"/>
</action>
<!-- 客户模块 -->
<action name="customer_*" class="com.hadwin.action.CustomerAction" method="{1}">
<interceptor-ref name="UserInterceptor"/>
<interceptor-ref name="defaultStack"/>
</action>
</package>
</struts>