1.struts中的配置
<interceptors> <!-- 声明拦截器 --> <interceptor name="logInterceptor" class="com.oa.util.LogInterceptor"></interceptor> <!-- 配置新的拦截器栈 --> <interceptor-stack name="myStack"> <interceptor-ref name="logInterceptor"> </interceptor-ref> <!-- 引入defaultStack --> <!-- 全局的每个action都会拦截 --> <interceptor-ref name="defaultStack"></interceptor-ref> </interceptor-stack> </interceptors> <global-results> <result name="logout" type="redirect">/jsp/login.jsp</result> </global-results> <action name="*_*" class="{1}Action" method="{2}"> <!-- 使用拦截器 --> <interceptor-ref name="myStack"></interceptor-ref> <result name="success">/jsp/{1}/{1}_{2}.jsp</result> </action>
2.拦截器类:
import org.apache.struts2.ServletActionContext; import com.oa.pojo.system.User; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; public class LogInterceptor extends AbstractInterceptor{ @Override public String intercept(ActionInvocation ai) throws Exception { // TODO Auto-generated method stub User user=(User) ServletActionContext.getRequest().getSession().getAttribute("login"); if(user==null){ ServletActionContext.getRequest().getSession().setAttribute("info", "用户已下线,请重新登录"); return "logout"; }else{ return ai.invoke(); } } }
3.拦截器与过滤器比较:
1、拦截器是基于java的反射机制的,而过滤器是基于函数回调
2、过滤器依赖与servlet容器,而拦截器不依赖与servlet容器
3、拦截器只能对action请求起作用,而过滤器则可以对几乎所有的请求起作用
4、拦截器可以访问action上下文、值栈里的对象,而过滤器不能
5、在action的生命周期中,拦截器可以多次被调用,而过滤器只能在容器初始化时被调用一次
在action的生命周期中,拦截器可以多次被调用,而过滤器只能在容器初始化时被调用一次
执行顺序 :过滤前 - 拦截前 - Action处理 - 拦截后 - 过滤后。
个人认为过滤是一个横向的过程,首先把客户端提交的内容进行过滤(例如未登录用户不能访问内部页面的处理);
过滤通过后,拦截器将检查用户提交数据的验证,做一些前期的数据处理,接着把处理后的数据发给对应的Action;
Action处理完成返回后,拦截器还可以做其他过程,再向上返回到过滤器的后续操作。