Notify user about session timeout in Java EE

My requirement is to notify the user with a pop-up message that the user session is about to time out after x seconds if the user does not perform any action on the web page.

An addition to this requirement is the dynamic change of x seconds in the pop-up window.

I am using Java EE environment.

+7
java java-ee jsp servlets session-timeout
source share
3 answers

Use HttpSession#getMaxInactiveInterval() and setTimeout() . There is no need for Ajax for this specific purpose unless you want to postpone a timeout on every client activity (poll).

Basic example:

 <script> var secondsBeforeExpire = ${pageContext.session.maxInactiveInterval}; var timeToDecide = 15; // Give client 15 seconds to choose. setTimeout(function() { alert('Your session is about to timeout in ' + timeToDecide + ' seconds!') }, (secondsBeforeExpire - timeToDecide) * 1000); </script> 

To reduce the time inside the message magically, instead of the main alert() you will need an overlay with a div in which you control the content through the HTML DOM tree and use another setTimeout() to 1 second to dynamically change the text.

Please note that this script must be serviced by JspServlet in order to get EL to work. So you need to put the script in the HTML <head> on the JSP page, or if you really want all JS in a separate *.js file, you need to enable the JspServlet *.js handle as well.

+11
source share

I do not think that Java / Java EE will be really useful here, as this needs to be handled on the client side (i.e. using JavaScript). One solution that I can think of would be to set some kind of timer that will notify the user a few minutes before the server timeout.

While searching on this issue, I found Eric Pascarello Refresh a user session with AJAX on the blog (and a reloaded version of Refresh a user session using Ajax - Round 2 ) that accurately describes such a solution (and use XMLHttpRequest to update the session). His session management Ajax script is available here .

+1
source share

Either it can be a simple servlet, Spring-MVC or Spring-Security, automatic exit is impossible without perfect client-side logic.
The application in question will have both types of requests

  • Ajax and
  • form submission / page reload

Automatic exit requires very thought out logic. Introducing my autologout function implementation with the following

Benefits.


1. No additional calls / requests are used to achieve this. taking into account the impact on productivity, if more than 10,000 active users and additional calls to achieve automatic exit.
2. One line configuration using a tag.
3. It works flawlessly, even if the user opens several tabs or multiple windows.
4. He informs you that up to 30 seconds of the session is invalid, so if you filled out the form and did not submit it, you can keep the session alive (extend the session with one click of the mouse). Thus, the user is less likely to lose unsaved data.


Use 1. Turn on the automatic logout script on the required JSP pages as follows.

  .... </body> <jsp:include page="../template/autologout-script.jsp"></jsp:include> </html> 

2. Create a JSP page, autologout-script.jsp, and add the code below. Note. Editing / customization is not required.

 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <script> $(document).ready(function() { var timeOutTimeInSeconds = ${ timeOutTimeInSeconds }; var showTimerTimeInSeconds= ${ showTimerTimeInSeconds }; var sessionCheckIntervalId = setInterval(redirectToLoginPage, timeOutTimeInSeconds * 1000); var timerDisplayIntervalId = setInterval(showTimer, (timeOutTimeInSeconds - showTimerTimeInSeconds) * 1000); var badgeTimerId; window.localStorage.setItem("AjaxRequestFired", new Date()); function redirectToLoginPage(){ //location.href = '<c:url value="/" />'+'${loginPageUrl}'; window.location.reload(); } $(document).ajaxComplete(function () { resetTimer(); }); $(window).bind('storage', function (e) { if(e.originalEvent.key == "AjaxRequestFired"){ console.log("Request sent from another tab, hence resetting timer") resetTimer(); } }); function resetTimer() { showTimerTimeInSeconds= ${ showTimerTimeInSeconds }; console.log("timeOutTimeInSeconds : "+timeOutTimeInSeconds) window.localStorage.setItem("AjaxRequestFired", new Date()); window.clearInterval(sessionCheckIntervalId); sessionCheckIntervalId = setInterval(redirectToLoginPage, timeOutTimeInSeconds * 1000); window.clearInterval(timerDisplayIntervalId); timerDisplayIntervalId = setInterval(showTimer, (timeOutTimeInSeconds - showTimerTimeInSeconds) * 1000); hideTimer(); } function showTimer() { $('#sessionTimeRemaining').show(); $('#sessionTimeRemainingBadge').html(showTimerTimeInSeconds--); window.clearInterval(timerDisplayIntervalId); badgeTimerId = setInterval(function(){ $('#sessionTimeRemainingBadge').html(showTimerTimeInSeconds--); }, 1000); } function hideTimer() { window.clearInterval(badgeTimerId); $('#sessionTimeRemaining').hide(); } }); </script> 

3. Configure session attributes to configure timeouts. Note. Configure this after creating the session. You can implement the sessionCreated HttpSessionListener method and set the following configuration according to your requirements.

 session.setMaxInactiveInterval(300); session.setAttribute("timeOutTimeInSeconds", 300); session.setAttribute("showTimerTimeInSeconds", 30); 

4. Add the HTML below to display the timer.
Note: you can move it to the autolog script page if you are good at CSS. Therefore, you can avoid adding this to every page.
Turn on the loader or add your own CSS.

 <span class="badge badge-primary" title="click to keep session alive" id="sessionTimeRemaining" onclick="ajaxSessionRefresh()" style="display:none;"> <i class="badge badge-danger" id="sessionTimeRemainingBadge" style="float:left">30</i> &nbsp; <small>Refresh</small> <i class="glyphicon glyphicon-refresh"></i> </span> 

enter image description here

It's all about a simple implementation of automatic logout. You can download a working example from my github repository
Autologout using a simple servlet example
Autologout using the Spring-Security Java configuration example
Autologout using Spring-Security XML configuration example

Explained Logic


Case 1: when loading a page
Here the logic is simple, when loading the page, set the interval equation timer to maxInactiveInterval. after a timeout redirect to the login page.
Case 2: Track AJAX Calls
Now when looking at AJAX requests, you can use .ajaxStart () or .ajaxComplete () jquery callbacks so that when you run any ajax request you can reset the interval.
Case 3: tracking the activity of multiple tabs / windows
Intertab communication is done to synchronize the state of each tab. Used localStorage when changing the event.

Constraints / Improvements Required
1. If the maximum allowed session is one, if the session is taken from another system, the AJAX request will not be executed. This needs to be processed in order to redirect to the login page.
2. Use ajaxStart () instead of ajaxComplete () to precisely synchronize idleTime values ​​between the server and browser.

Requirements
1. jquery

Comparison of alternatives to the current implementation


1. Setting the header update in the http response. (Does not work for AJAX requests)

 response.setHeader("Refresh", "60; URL=login.jsp"); 
  1. Customizing the meta meta tag in HTML (not working for AJAX requests)
 <meta http-equiv="refresh" content="60; url=login.jsp"> 
  1. Configure Activity Checking Supports a session by re-issuing an AJAX request. Monitors downtime and sends an exit request after a timeout.
    Without a doubt, this is a good one with simple logic. But I just want to draw my observations.
    • Performance impact if 2 requests are executed per minute to maintain session activity and 50,000 active users. 100,000 requests per minute.
    • Relationship between tabs If two tabs are open, one tab receives activity, but the other tab does not receive activity, this tab launches a logout request and invalidates the session, even if activity is present on another tab. (But can be processed)
    • Force Logout Approach This client dominates the server to terminate the session.
0
source share

All Articles