<

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x

Ajax way of Session TimeOut / Extension

Published on
12,476 Points
6,376 Views
1 Endorsement
Last Modified:
Approved
Murali Murugesan
Visit codestore.com.au
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
0 Comments

Featured Post

Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

Learn how to collaborate with office 365 Office Online
If you, like me, have a dislike for using Online Subscription anti-spam services, then this video series is for you. I have an inherent dislike of leaving decisions such as what is and what isn't spamming to other people or services for me and insis…

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month