Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Notify user about session timeout in Java EE

My requirement is to notify the user with a popup saying that the user session is about to time out in x seconds in case user does not perform any activity on the web page.

Addition to this requirement is to decrement the value x seconds dynamically in the popup.

The environment I use is Java EE.

like image 607
Eager Learner Avatar asked Dec 31 '09 12:12

Eager Learner


People also ask

How do I alert someone before session timeout?

First things first: When you want to warn the user 5 minutes before the 15 minutes timeout, the warning shoud be displayed at 10 minutes after page load. setTimeout( function() { alert("Your session will expire in 5 minutes."); }, 10*60*1000);

What is the default session timeout?

The default is 10 minutes. Session. Timeout has no hard-coded limit. Most Web administrators set this property to 8 minutes.


2 Answers

Make use of HttpSession#getMaxInactiveInterval() and setTimeout(). There's no need for Ajax in this particular purpose, unless you want to postpone the timeout on every client activity (polling).

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 decrement the time inside the message magically, then instead of the basic alert() you'll need an overlay with a div wherein you have control over the content through HTML DOM tree and make use of another setTimeout() on 1 second to change the text dynamically.

Note that this script has to be served by the JspServlet to get the EL to work. Thus, you need to put the script in the HTML <head> of the JSP page, or if you really want to have all the JS in a separate *.js file, then you need to let the JspServlet handle any *.js requests as well.

like image 118
BalusC Avatar answered Nov 02 '22 23:11

BalusC


I don't think that Java/Java EE will be really helpful here as this need to be handled on the client-side (i.e. using JavaScript). One solution I can think of would be to set a kind of timer that would notify the user a few minutes before the server's timeout.

While googling about this, I found Eric Pascarello's Update User's Session with AJAX blog post (and the reloaded version Updating User Session with Ajax - Round 2) that precisely describes such a solution (and use an XMLHttpRequest to update the session). His Ajax Session Management script is available here.

like image 41
Pascal Thivent Avatar answered Nov 03 '22 00:11

Pascal Thivent