<

Ajax way of Session TimeOut / Extension

Published on
12,399 Points
6,299 Views
1 Endorsement
Last Modified:
Approved
Hello World !,

Thanks :
My Sincere thanks to @Michael Male who encouraged me to write an article on this in my  blog.


Introduction:

      There are several technical issues a developer may face in his everyday routine. Many of it would be as itchy as dandruff  :) , and there are always different ways a particular problem can be solved or dealt with. But, the best /recommended approach works fine in most of the cases.
       
        One such issue is when a web session expires without any prior notice to the user, who might be busy talking in a meeting, chatting (of course official), answering a phone call, or just out for a quick walk. The returning user might be annoyed if the page says that "Your session expired" after keying in a long form of data. If you've experienced this (and who hasn't), you know how annoying it can be.

        So, I present here one possible solution of addressing this using AJAX. Let's get down to business straight away.

The Ajax way:

     This article is intended primarily for readers who are aware of AJAX (at least at a basic level), so I will go directly to the functional part of the solution.

function newXMLHttpRequest()
{
        var xmlreq = false;    
        if (window.XMLHttpRequest)
        {
          xmlreq = new XMLHttpRequest();
        }
        else if (window.ActiveXObject)
        {
            try
            {
               xmlreq = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e1)
            {
                try
                {            
                 xmlreq = new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch (e2)
                {
                  xmlreq = false;
                }
            }
        }
    return xmlreq;
}

Open in new window


 The above code snippet can be implemented in different flavours but, the basic functionality is to create an XMLHttpRequest object irrespective of the browser.

function getReadyStateHandler(req, responseXmlHandler)
{
        return function ()
        {
           if (req.readyState == 4)
           {
             if (req.status == 200)
             {
               responseXmlHandler(req.responseXML);
             }
            else
             {
               alert("HTTP error "+req.status+": "+req.statusText);
             }
          }
    }
}

Open in new window


   The above function is the callback function for every AJAX call made using the XMLHttpRequest object. To ensure on page load the session is alive, make a call to validateAndExtendSession() to ensure session is active, and there is also the issue that a browser back button is clicked after logout.

            // to ensure on page load, the session is still active
            window.onload=function(){
		validateAndExtendSession(); 
	    }
	
	    window.onunload=function(){} // fix for Firefox when browser back button is clicked

Open in new window


           The above onload can be replaced with Jquery as below,

           <script src="jquery.js"></script>	
          <script>
	          $(document).ready(function(){
                        validateAndExtendSession();  
                   });     
         </script>

Open in new window


                  
          function validateAndExtendSession(){
                   var req = newXMLHttpRequest();
                   req.onreadystatechange = getReadyStateHandler(req, updateSessionInfo);
                   req.open("GET", "/servlet/SessionHandler", true); //modify to point to ur servlet
                   req.send(""); //use POST when queryparameters are used
          }

           function updateSessionInfo(sessionXML){
                 var session = sessionXML.getElementsByTagName("session")[0];
                 var userid = session.getAttribute("userid");    
                   if(userid == 'null' || userid == null){
                      msgToUser();
                   }
            }

            function msgToUser(){
               alert("Session already expired. Please re-login to the application");
	       //redirect to login page since the session has already expired and no more extension possible
            }

            function promptUser(){
                   if (confirm('Your login session will expire in 5 minute.Would you like to extend the session?')){
                           validateAndExtendSession();                           
                   }
            }

             function setSessionTimeout(){
                  // prompt timeout message 5 mins before timeout
                  // it is assumed to be 30 mins before timeout
                  setTimeout('promptUser()', 25 * 60 * 1000);
            }

             //default call to the timer function
            setSessionTimeout();

Open in new window

       
           So, the above code snippet is an extensive script for automatic session timeout monitoring and shows an alert to indicate the session extension. Now let's take a look at what the servlet doGET (use doPOST in case you have query parameters set in the ajax call) handling this AJAX request would look like,

	session = request.getSession();
	StringBuffer xml = new StringBuffer();
	xml.append("<?xml version=\"1.0\"?>\n");
	xml.append("<session userid=\"" + (String)session.getAttribute(userId) + "\">\n");
	xml.append("</session>\n");

	response.setContentType("text/xml");
	response.getWriter().write(xml.toString());
	response.getWriter().flush();

Open in new window


               In the above code snippet we don't do much apart from fetching the userid from session and setting it to the XML attribute value. This hit to the server ensures that the session-timeout is reset back to 0. So when there is an alert (say at 25 mins, considering 30 mins is the session expiry time) clicking on OK would give a hit to the servlet and thereby exending the session.

    If the user is late in reacting to the alert, as soon as the OK button is hit , the next alert stating  "Session already expired. Please re-login to the application" would be shown and redirected to the login page appropriately.

Hope this article gives you some quick insight in implementing the session extension.

Limitations of this Solution:

1. If the user's browser has Javascript disabled, the above code (Javascript) will not execute.
2. This solution was tested for browsers IE,Firefox,Safari.
3. As the example servlet code indicates, it's purely for JAVA applications.
4. This solution was tested in the following environment -  JSP, JAVASCRIPT, JAVA 5, TOMCAT 5.5 & Sun-One server.

Happy Coding!.

-Murali*
1
Comment
0 Comments

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Join & Write a Comment

Key to your CPU's ability to stay cool is to use the right amount of thermal paste and apply it correctly. In other words you want as much thermal conductivity between CPU and the cooling block. Use a quality thermal paste and apply it in a manner…
This is Part-2 of Learning to use the Power of Mailwasher Pro so if you haven't watched Part-1 yet, I urge you to do so before watching this video. Click this link to watch Part-1 (https://www.experts-exchange.com/videos/56638/Learn-to-use-the-POWER…
Next Article:

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month