Article: Gracefully Timing Out A Session Using Ajax & CSS


Summary:

Ajax and CSS have come a long way and the year 2006 looks like the year of Web 2.0 where usability is going to be the key that drives websites. With that in mind, I've decided to illustrate a clean and graceful way to timeout your session in your server.

What does it do:


How many times have you visited sites where you walk away and come back and click on a link and it sends you to a session timeout page where they make you login again. Well, I think with some clever CSS and Ajax you can present the user with a UI where they have a chance to refresh their session without timimg out and if they walk away too long we then gracefully notify the user that their session has timed out. First lets get familiar with the interface. Click here for the demo and you can return back to this article when you are done seeing the demo.

For the not so patient:


You can download the zip with all the sample files here.

Directions:


  • Unzip contents into a directory on your webserver.
  • Edit the line at the bottom of demo.jsp and change it to point to your server:
    <SCRIPT SRC="<%=request.getContextPath()%>/technotes/gracefuldemo/_timer.jsp"></SCRIPT>
  • Edit _timer.jsp and set the variables such as timeout, alertBeforeSeconds, loginURL and url
  • Compile RenewSessionServlet.java and drop it into /WEB-INF/classes directory as appropriate.
  • Add to your /WEB-INF/web.xml the Servlet context. In Tomcat, I was not successful in making a JSP response feed. So I used a Servlet to handle the refresh.
  •     <servlet>
          <servlet-name>GracefulDemoServlet</servlet-name>
          <servlet-class>com.avedatech.GracefulDemo.RenewSessionServlet</servlet-class>
        </servlet>
        
        <servlet-mapping>
          <servlet-name>GracefulDemoServlet</servlet-name>
          <url-pattern>/renewSession.do</url-pattern>
        </servlet-mapping>
    		
  • Now if you visit the demo page on your server, you should now see the demo in action.

To understand the Ajax call and how it works, you can read the previous article here.

Graceful Timeout Deconstructed:


Step-1: Parts of the puzzle
  • CSS is used in creating the transparency layer that you see as well as the modal dialog boxes that we have created and the button functionality.
  • AJAX is used to send a request back to the server and thereby refreshing the session for [n] seconds.
  • JavaScript is used to make the AJAX XMLHttpRequest() as well as the window.setTimeout() & window.clearTimeout(id) to time the event.
  • Servlet/JSP technology is used to send back an XML feed after the servlet is invoked to confirm the refresh of the session.
Step-2: CSS

/* Modal Dialog */


#overlaybase 
{
	z-index:100;
	background-color:#476685;
	position:absolute;
	top:0;
	left:0;
	width:120%;
	height:2600px;
	opacity:.50;
	filter:progid:DXImageTransform.Microsoft.Alpha(opacity=50);
	-moz-opacity:.50;
	display: none;	
	text-align: center;
}

#overlaytitle
{
	background-color: #4682B4;
	color: White;
	text-align: left;	
	font-weight: bold;
	height: 20px;
	padding-left: 10px;
	border-bottom: 1px solid Black;
	font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;	
}

#overlaybody
{
	background-color: #FFFFFF;
	color: #000000;
	text-align: center;
	font-weight: normal;
	font-size: 12px;
	padding: 10px;
	font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;	
}

#overlaytext
{
	background-color: #FFFFFF;
	color: #000000;
	text-align: center;
	font-weight: normal;
	font-size: 12px;
	font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
	padding: 10px;	
}

#overlay 
{
	position:absolute; 
	left:300px;
	top:150px;
	width: 350px;	
	border: navy solid 1px; 
	padding: 10px;
	z-index:102;
	padding:0;
	filter:progid:DXImageTransform.Microsoft.dropshadow(OffX=3, OffY=3, Color='#3D4B5A', Positive='1'); /* Dropshadow for IE */
	display: none;
}

a.button {
	background-color: #FFDB48;
	padding-bottom: 3;
	padding-left: 5;
	padding-right: 5;
	padding-top: 3;
	border-bottom: 1px solid Gray;
	border-right: 1px solid Gray;
	border-top: 1px solid Silver;
	border-left: 1px solid Silver;
	text-decoration: none;
	color: Blue;	
	font-weight: normal;
	font-size: 10px;
	font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
}
a.button:hover{
	background-color: #E5B700;
	padding-bottom: 3;
	padding-left: 5;
	padding-right: 5;
	padding-top: 3;
	border-bottom: 1px solid Silver;
	border-right: 1px solid Silver;
	border-top: 1px solid Gray;
	border-left: 1px solid Gray;
	text-decoration: none;
	color: #8B0F07;
	font-weight: normal;
	font-size: 10px;
	font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
}
		

#overlaybase  creates the transparent screen that you see. To understand the Z-index and how that works, refer to this article.
Step-3: AJAX
Whenever you hit the refresh button the browser makes a call to the "/renewSession.do" to refresh the session. If we were to make the call in the foreground then the information thats on the current screen will be lost. For example, if they are in the middle of a transaction then they will have to reenter the information. So we make an AJAX call in the background. Click here to see what gets returned as a result of the call. To understand the AJAX call refer to the AJAX article available on the top-left of the navigation.
Step-4: Javascript
Rather than document the entire javascript, let me highlight the parts that make up the effects:
function displayOverlay()
{
	document.getElementById("overlaybase").style.display = "block";
	document.getElementById("overlay").style.display = "block";		
}

function hideOverlay()
{
	document.getElementById("overlaybase").style.display = "none";
	document.getElementById("overlay").style.display = "none";	
}

function displayTextActive()
{
	document.getElementById("overlaybody").innerHTML = textActive;
}

function displayTextTimedOut()
{
	document.getElementById("overlaybody").innerHTML = textTimedOut;
}
		

In the CSS sheet we set #overlaybase{ display: none; } which hides it to begin with and in displayOverlay() function we are displaying it back up as a block. To hide it we call the function hideOverlay() which once again hides the DIV.
Similarly we use the .innerHTML function to replace the content within the dialog box.
Step-5: Servlet

This is a pretty simple servlet that just sends back a XML message back. All we care about is that we successfully made a request in the background to a JSP or Servlet page to refresh the session timout on the server.
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{        
    response.setContentType("text/xml");
    response.getOutputStream().println("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
    response.getOutputStream().println("<response>");
    response.getOutputStream().println("<result>Your session has been renewed.</result>");
    response.getOutputStream().println("</response>");
    response.getOutputStream().println("\n\n");
}  
		

Things to consider

Including the JavaScript on every page is very clobersome and it's one more thing to do on every page. So consider some sort of templating such as SiteMesh or MonkeyGrease (I said it right! MonkeyGrease not GreaseMonkey) to insert the script at the close of the body tag.

Feel free to download the ZIP with all the files and try it out on your server.

Send me your comments here.

Created By: Venkatt Guhesan at Aveda Technology, Inc.
Last Updated: Friday, December 23, 2005.

Happy Coding & Happy Holidays!!!