Tuesday, February 21, 2012

Java/J2EE web apps: Handling session expiration when using JQuery to populate a div

It took me a little while and a lot of googling to figure this one out and to get it just right, so I figured I'd share it.

I'm using Spring MVC with Spring Security and JQuery.  I have lots of places where I'm populating a div using JQuery's post() or load() methods.  However, if my session had expired, the destination div element would get populated with my login page.  To get around this, I learned about JQuery's global AJAX event handlers (http://api.jquery.com/category/ajax/global-ajax-event-handlers/).

What wasn't totally obvious to me when I first looked at it was that you can attach your event handler function to any old element.  In my case I just picked the <head> element since I know there's only one of them.  That handler will still be called for all AJAX calls, no matter what element they were called from.

Here is my setup code - I placed it within the of my header JSP.  You can see examples of how I used the same technique for globally handling errors, and showing a "waiting" icon while a request is processing.

<script language="JavaScript">
 //global ajax event handlers
 $('html').ajaxSuccess(
  function(event, xhr, ajaxOptions) {
   //if the response contains the string '***LOGIN***' (which appears as a 
   //comment in login.jsp), log the user out
   if(xhr.responseText.indexOf('***LOGIN***') >= 0) {
    window.location.href = '<c:url value="/j_spring_security_logout"/>';
   }
  }
 );
 
 $('html').ajaxStart(
  function() {
   $('#waitingIcon').show();
  }
 );
 
 $('html').ajaxStop(
  function() {
   $('#waitingIcon').hide();
  }
 );
 
 $('html').ajaxError(
  function() {
   $('#globalErrorDiv').html('<div class="validationError">We\'re sorry, an error \
   occurred while processing. Please try again.</div>');
  }
 );
</script>

No comments:

Post a Comment