1.拦截器(Interceptor):拦截器是Struts2的核心,Struts2的众多功能都是通过拦截器来实现的。
拦截器的配置
1)编写实现Interceptor接口的类。
2)在struts.xml文件中定义拦截器。
3)在action中使用拦截器
一旦定义了自己的拦截器,将其配置到action上后,我们需要在action的最后加上默认的拦截器栈:defaultStack。
默认是对execute()方法进行拦截
定义拦截器时可以直接继承AbstractInterceptor抽象类(该类实现了Interceptor接口,并且对init和destroy方法进行了空实现),然后实现其抽象方法intercept即可。
方法过滤拦截器(可以对指定方法进行拦截的拦截器)。
在方法过滤拦截器中,如果既没有指定includeMethods参数,也没有指定execludeMethods参数,那么所有的方法都会被拦截,也就是说所有的方法都被认为是includeMethods的;如果仅仅指定了includeMethods,那么只会拦截includeMethods中的方法,没有包含在includeMethods中的方法就不会被拦截。
拦截器的三种实现方法:
1.实现Interceptor接口
2.继承AbstractInterceptor抽象类
3.继承MethodFilterInterceptor抽象类
验证用户登录的拦截器
public class LoginInterceptor extends AbstractInterceptor{
@Override
public String intercept(ActionInvocation invocation) throws Exception {
Map map = invocation.getInvocationContext().getSession();
if(null == map.get("userinfo")){
return Action.LOGIN;
}
return invocation.invoke();
}
}
编辑struts.xml文件,定义拦截器,并重新定义拦截器栈,设置默认拦截器栈。