session超时 struts2自定义拦截器

实例功能:当用户登陆后,session超时后则返回到登陆页面重新登陆。
为了更好的实现此功能我们先将session失效时间设置的小点,这里我们设置成2分钟,其中默认为30分钟
1、修改web.xml
<session-config>
<session-timeout>2</session-timeout>
</session-config>

2、实现自定义拦截器类
public class SessionInterceptor extends AbstractInterceptor {

private static final long serialVersionUID = 1L;

@SuppressWarnings("unchecked")
@Override
public String intercept(ActionInvocation actionInvocation) throws Exception {
Map session=actionInvocation.getInvocationContext().getSession();
Action action = (Action) actionInvocation.getAction();
if (action instanceof LoginAction) {
return actionInvocation.invoke();
}
String userId = (String) session.get("userId");
//如果用户为空则跳到LOGIN页面,否则退出拦截
System.out.println("用户ID"+userId);
if(userId==null){
return "error";
}else{
return actionInvocation.invoke();
}
}
}

3、struts.xml中定义并使用此拦截器
<!-- 定义一个拦截器 -->
<interceptors>
<interceptor name="sessionout" class="com.base.interceptor.SessionInterceptor"></interceptor>
<interceptor-stack name="mydefault">
<interceptor-ref name="defaultStack"/>
<interceptor-ref name="sessionout"/>
</interceptor-stack>
</interceptors>

<!-- 定义全局Result -->
<global-results>
<!-- 当返回login视图名时,转入/login.jsp页面 -->
<result name="error" >/login.jsp</result>
</global-results>

4、在其他struts2.xml配置文件中引用此拦截器配置
<action name="sign" class="com.huge.email.sign.SignAction">
<interceptor-ref name="mydefault"/>
</action>

其中需要注意的是当自定义拦截器的时候由于没有对登录的action进行拦截,自定义拦截器中通过代码
Action action = (Action) actionInvocation.getAction();
if (action instanceof LoginAction) {
return actionInvocation.invoke();
}
没有对登录进行拦截,如果对登录进行了拦截则永久无法登录,所以这里import了
import com.opensymphony.xwork2.Action;
所以这里就需要其他的action类继承actionSupport类,因为actionSupport同样继承与action类!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值