版本:struts2.1.6
執行個體功能:當使用者登陸後,session逾時後則返回到登陸頁面重新登陸。
為了更好的實現此功能我們先將session失效時間設定的小點,這裡我們設定成1分鐘
修改web.xml [c-sharp] view plain copy <session-config> <session-timeout>1</session-timeout> </session-config>
此執行個體用到的jsp頁面及登陸所涉及到的相關代碼請參考:
Struts2自訂攔截器執行個體—登陸許可權驗證
實現自訂攔截器類 [c-sharp] view plain copy package com.ywjava.interceptor; import java.util.Map; import com.opensymphony.xwork2.Action; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; import com.ywjava.action.LoginAction; import com.ywjava.utils.Constants; public class SessionIterceptor extends AbstractInterceptor { @Override public String intercept(ActionInvocation actionInvocation) throws Exception { ActionContext ctx = ActionContext.getContext(); Map session = ctx.getSession(); Action action = (Action) actionInvocation.getAction(); if (action instanceof LoginAction) { return actionInvocation.invoke(); } String userName = (String) session.get(Constants.USER_SESSION); if (userName == null) { return Action.LOGIN; } else { return actionInvocation.invoke(); } } }
struts.xml中定義並使用此攔截器 [c-sharp] view plain copy <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <package name="authority" extends="struts-default"> <!-- 定義一個攔截器 --> <interceptors> <interceptor name="authority" class="com.ywjava.interceptor.LoginInterceptor"> </interceptor> <interceptor name="sessionout" class="com.ywjava.interceptor.SessionIterceptor"></interceptor> <!-- 攔截器棧 --> <interceptor-stack name="mydefault"> <interceptor-ref name="defaultStack" /> <interceptor-ref name="authority" /> <interceptor-ref name="sessionout"/> </interceptor-stack> </interceptors> <!-- 定義全域Result --> <global-results> <!-- 當返回login視圖名時,轉入/login.jsp頁面 --> <result name="login">/login.jsp</result> </global-results> <action name="loginform" class="com.ywjava.action.LoginFormAction"> <result name="success">/login.jsp</result> </action> <action name="login" class="com.ywjava.action.LoginAction"> <result name="success">/welcome.jsp</result> <result name="error">/login.jsp</result> <result name="input">/login.jsp</result> </action> <action name="show" class="com.ywjava.action.ShowAction"> <result name="success">/show.jsp</result> <!-- 使用此攔截器 --> <interceptor-ref name="mydefault" /> </action> </package> </struts>
當我們登陸後一分鐘不做任何操作重新整理後則會跳轉到登陸頁面
轉載自:http://blog.csdn.net/java_cxrs/article/details/5519743