java中的拦截器

使用拦截器判断用户是否登录与是否登录超时,struts2中

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处理完成返回后,拦截器还可以做其他过程,再向上返回到过滤器的后续操作。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值