Our application logs off after 30 min and gets redirected to login page,i am specifying session timeout in web.xml and using a requestProcessor for redirecting.I want to show to the user a message saying your session got expired once the session expires,how can i do that.Auto log off ? I wuold like to prompt the error message on the page"The session is timout, please login again" . Then how could I detect the session is timeout? will any methods trigger automatically?
If you're using servlet sessions, you can check to see if the session the jsp / servlet is returning is new using the isNew() method. If yes, then the user's session has expired and you can display the relevant messages.
Create a Listener class implementing HttpSessionListener
and define it in web.xml
This will notify you when any session is destroyed. Use the sessionDestroyed()
method.
See a full example here:
http://www.mkyong.com/servlet/a-simple-httpsessionlistener-example-active-sessions-counter/
Include a javascript utility function inside your JSP and ping the server every 31 minutes. The above mentioned utility function should be using setTimeout() JS function internally.
setTimeout ( "checkServerSession()", /* intervalInMilliSeconds */ 31000);
Note that
checkServerSession()
is a regular JS function which may fire HTTP requests. If the request is successful session exists otherwise show the prompt to the user.
You can use Servlet's HttpSession#getMaxInactiveInterval()
to get the remaining lifetime of the current session and you can use JavaScript's setTimeout()
to timeout a function callback.
1 + 1 = 2, so here's a basic example which needs to be placed inside a JSP (so that the EL, those ${}
things, can do its work):
<script>
setTimeout(function() {
alert('Your session is timed out!'); // Display alert.
window.location = 'logout.jsp'; // Then redirect to logout page.
}, ${pageContext.session.maxInactiveInterval} * 1000); // It returns seconds, but setTimeout expect milliseconds.
</script>