Frameworks >> JavaScript >> Struts >> Web Applications
how to force page to login after struts2 session timeout
In order to show login page automatically when the session has expired. There are two level of code changes required. One is Javascript changes and the other is struts 2 interceptor changes.
The javascript changes will automatically make the application to show login page when the session has expired and the interceptor will help in showing the login page when the javascript code could not be executed and the user clicked on a link/button in the application.
The javascript code will not be executed when the user closes the browser (with currently open pages to be shown next time) before session timeout and then opens the browser after the time interval when session would have expired (say next day).
Javascript code:
The below javascript code should be included in a common file so that our javascript code executes on all pages in the application.One can also paste this code into a .js file and then include that .js file in a common file.
If you are wondering what is meant by common file then paste the javascript session timeout code in the header.jsp (header.xyz) file of your application which will ensure that the javascript code is executed at all times.
You need to invoke the function timeIt(); on the onload event of header/sidebar/footer page.
function Minutes(data) {
for (var i = 0; i < data.length; i++)
if (data.substring(i, i + 1) == ":")
break;
return (data.substring(0, i));
}
function Seconds(data) {
for (var i = 0; i < data.length; i++)
if (data.substring(i, i + 1) == ":")
break;
return (data.substring(i + 1, data.length));
}
function Down() {
sec--;
if (sec == -1) {
sec = 59; min--;
}
if(min==3 && sec == 0){
var d = new Date();
var hours = d.getHours();
var minutes = d.getMinutes();
if(minutes<10){ br=""> minutes = "0" + minutes;
}
alert('Message from Application at '+hours+':'+minutes+' - nnYou
have been inactive and have not saved your work for last 27 Minutes.n
Please save your work in next 3 minutes to avoid any Data Loss due to Session timeout.');
}
if (min == 0 && sec == 0) {
window.status = "Your session has timed out."
document.location.href="Login";
}else {
down = setTimeout("Down()", 1000);
}
}
function timeIt() {
min = 1 * Minutes("30:00");
sec = 0 + Seconds("30:00");
Down();
}
It is worth mentioning here that the struts2 session timeout in above code is set as 30 minutes. You need to specify the same time interval in timeIt() function as you have mentioned in your web.xml file.
Interceptor Code:
Create a new interceptor class in your struts2 application as:
package com.test.helper;
import java.util.Map;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.ValidationAware;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class SessionCheckInterceptor extends AbstractInterceptor {
private static final String USER_KEY = "username";
public String intercept(ActionInvocation invocation) throws Exception {
ActionProxy proxy = invocation.getProxy();
Map results = proxy.getConfig().getResults();
Map session = invocation.getInvocationContext().getSession();
if(session.get(USER_KEY) == null) {
addActionError(invocation, "Your session has expired.");
return "invalidsession";
}
return invocation.invoke();
}
private void addActionError(ActionInvocation invocation, String message) {
Object action = invocation.getAction();
if(action instanceof ValidationAware) {
((ValidationAware) action).addActionError(message);
}
}
}
Now we need to configure the Session check interceptor in struts.xml as:
<struts> <package name="default" extends="struts-default"> <result-types> <result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult"></result-type> </result-types></package></struts> <interceptors> <interceptor name="SessionCheck" class="com.tcs.kbank.helper.SessionCheckInterceptor"></interceptor></interceptors> <interceptor-stack name="newStack"> <interceptor-ref name="SessionCheck"></interceptor-ref> <interceptor-ref name="defaultStack"></interceptor-ref> </interceptor-stack> ....................................... ....................................... ....................................... <action name="xyz" class="com.test.xyz"> <interceptor-ref name="newStack"></interceptor-ref> <result name="invalidsession">/jsp/login.jsp</result> <result name="welcome" type="tiles">welcome</result> </action> .......................................................... ........................................................
In struts.xml, we need to add the interceptor to every action for which we want the session validation to be done. There are pages like logout which don’t require session validation and the interceptor can be avoided for these actions.
If you find any issue while configuring the automatic session expire login page then leave a comment and I will try resolve your issue.
JavaScript Tutorials
Local and Global Variables in JavaScript
Value of one Variable as name for another Variable
Comments
Anonymous
@Raja_ashok
Do you mean that you want to invoke the invalidate() function on session object after 15 minutes?
1) If yes then configure that time in web.xml after which you need not invoke any function.
2) Otherwise if the overall scenario doesn’t permit configuring session timeout in web.xml then use the TimerTask class of Java to schedule the task after 15 minutes. Here you will schedule the task to run after 15 minutes of user login and cancel/reschedule the task if user performs some activity. 3) The code in this article is for Javascript alert and then forwarding the user to login page automatically when the session would have expired on the server.
Hope I am clear. Do let me know in case any further confusion



Raja_ashok
I am looking for the session invalidation code for being used in struts2 application. I am trying to invalidate the session after 15 mins of user inactivity but the session is not getting invalidated. Please help me.