实例功能:当用户登陆成功后,若session超时则返回到登陆页面重新登陆。
1、http://localhost:8083/struts2/user.jsp 用户登陆
2、http://localhost:8083/struts2/login/loginHelloWorld.do 若登陆成功,会跳转到成功页面,否则会跳转到session失效提示页面
配置session失效时间,修改web.xml
<!-- 设置session失效时间,这里我们设置成1分钟后失效 --> < session - config > < session - timeout > 1 </ session - timeout > </ session - config >
登陆页面
<% @ page language = " java " import = " java.util.* " pageEncoding = " UTF-8 " %> <% request.getSession().setAttribute( " user " , " 林计钦 " ); %> 用户已经登录
Action类
package com.ljq.action; public class HelloWorldAction { public String login() { return " success " ; } }
session拦截器
package com.ljq.interceptor; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; /** * 自定义session拦截器,30s后失效 * * */ @SuppressWarnings( " serial " ) public class SessionIterceptor extends AbstractInterceptor{ @Override public String intercept(ActionInvocation invocation) throws Exception { ActionContext ctx = invocation.getInvocationContext(); String user = (String)ctx.getSession().get( " user " ); if (user != null && user.equals( " 林计钦 " )){ return invocation.invoke(); } // 如果超时,返回提示页面 return " index " ; } }
struts.xml配置文件
<? xml version = " 1.0 " encoding = " UTF-8 " ?> <! DOCTYPE struts PUBLIC " -//Apache Software Foundation//DTD Struts Configuration 2.0//EN " " http://struts.apache.org/dtds/struts-2.0.dtd " > < struts > < constant name = " struts.i18n.encoding " value = " UTF-8 " /> < constant name = " struts.enable.DynamicMethodInvocation " value = " false " /> < constant name = " struts.action.extension " value = " do " /> < package name = " login " namespace = " /login " extends = " struts-default " > < interceptors > <!-- 自定义拦截器 --> < interceptor name = " permission " class = " com.ljq.interceptor.SessionIterceptor " /> <!-- 配制默许的拦截器到拦截器栈 --> < interceptor - stack name = " permissionStack " > <!-- 此处先后顺序好像没影响哦,我尝试过是没影响的 --> < interceptor - ref name = " permission " /> < interceptor - ref name = " defaultStack " /> </ interceptor - stack > </ interceptors > <!-- 配置默认的拦截器 --> < default - interceptor - ref name = " permissionStack " /> <!-- 全局变量 --> < global - results > < result name = " success " >/ WEB - INF / page / message.jsp </ result > </ global - results > < action name = " *HelloWorld " class = " com.ljq.action.HelloWorldAction " method = " {1} " > <!-- 超时返回登录页面 --> < result name = " index " >/ index.jsp </ result > </ action > </ package > </ struts >