实例功能:当用户登陆后,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类!
分享到:
相关推荐
Struts通过拦截器实现登录后跳转到登录前页面
dwz框架实现拦截器 session超时跳转登陆页面 DWZ框架 struts2拦截器 session超时
8.8 拦截器 332 8.9 依赖注入 335 8.9.1 EJB注入 336 8.9.2 资源注入 339 8.10 配置EJB引用 340 8.11 使用计时器进行任务调度 342 8.12 本章小结 345 第9章 消息驱动EJB 346 9.1 JMS和EJB 347 9.1.1 为什么使用MDB ...
\contentsline {chapter}{Contents}{2}{section*.1} {1}Java基础}{17}{chapter.1} {1.1}基本语法}{17}{section.1.1} {1.2}数字表达方式}{17}{section.1.2} {1.3}补码}{19}{section.1.3} {1.3.1}总结}{23}{...
9.2 利用拦截器(Interceptor)生成审计日志 9.3 Hibernate的事件处理机制 9.4 批量处理数据 9.4.1 通过Session来进行批量操作 9.4.2 通过StatelessSession来进行批量操作 9.4.3 通过HQL来进行批量操作 ...
9.2 利用拦截器(Interceptor)生成审计日志 9.3 Hibernate的事件处理机制 9.4 批量处理数据 9.4.1 通过Session来进行批量操作 9.4.2 通过StatelessSession来进行批量操作 9.4.3 通过HQL来进行批量操作 ...
9.2 利用拦截器(Interceptor)生成审计日志 9.3 Hibernate的事件处理机制 9.4 批量处理数据 9.4.1 通过Session来进行批量操作 9.4.2 通过StatelessSession来进行批量操作 9.4.3 通过HQL来进行批量操作 ...
9.2 利用拦截器(Interceptor)生成审计日志 9.3 Hibernate的事件处理机制 9.4 批量处理数据 9.4.1 通过Session来进行批量操作 9.4.2 通过StatelessSession来进行批量操作 9.4.3 通过HQL来进行批量操作 ...
25.1 AOP联盟(MethodInvocation)安全拦截器 197 25.1.1显式MethodSecurityInterceptor配置 197 25.2 AspectJ(JoinPoint)安全拦截器 198 26.基于表达式的访问控制 200 26.1概述 200 26.1.1通用内置表达式 201 ...