DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Frameworks
  4. Session Timeout Handling on JSF AJAX request

Session Timeout Handling on JSF AJAX request

Boris Lam user avatar by
Boris Lam
·
Dec. 06, 12 · Interview
Like (2)
Save
Tweet
Share
19.60K Views

Join the DZone community and get the full member experience.

Join For Free

When we develop JSF application with AJAX behaviour, we may experience the problem in handling timeout scenario of Ajax request. For example, if you are using J2EE Form-based authentication, a normal request should be redirected to the login page after session timeout. However, if your request is AJAX, the response could not be treated properly on the client-side. User will remain on the same page and does not aware that the session is expired.

Many people proposed solution for this issue. The followings are two of possible solutions involve the use of Spring security framework:
1. Oleg Varaksin's post
2. Spring Security 3 and ICEfaces 3 Tutorial

Yet, some applications may just using simple mechanism to stored their authentication and authorization information in session. For those application that is not using Spring Security framework, how can they handle such problem? I just modified the solution proposed by Oleg Varaksin a bit as my reference.


First, create a simple session scoped JSF managed bean called "MyJsfAjaxTimeoutSetting".
The main purpose of this POJO is just to allow you to configure the redirect url after session timeout in faces-config.xml. You may not need this class if you do not want the timeout URL to be configurable.

public class MyJsfAjaxTimeoutSetting {
  
 
 public MyJsfAjaxTimeoutSetting() {
 }
 
 private String timeoutUrl;
  
  
 public String getTimeoutUrl() {
  return timeoutUrl;
 }
 
 public void setTimeoutUrl(String timeoutUrl) {
  this.timeoutUrl = timeoutUrl;
 }
 
  
}

Second, create a PhaseListener to handle the redirect of Ajax request.
This PhaseListener is the most important part of the solution. It re-creates the response so that the Ajax request could be redirect after timeout.

import org.borislam.util.FacesUtil;
import org.borislam.util.SecurityUtil;
import java.io.IOException;
import javax.faces.FacesException;
import javax.faces.FactoryFinder;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.faces.render.RenderKit;
import javax.faces.render.RenderKitFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.primefaces.context.RequestContext;
 
public class MyJsfAjaxTimeoutPhaseListener implements PhaseListener
{
 
 public void afterPhase(PhaseEvent event)
 {
 }
  
 public void beforePhase(PhaseEvent event)
 {  
  MyJsfAjaxTimeoutSetting timeoutSetting = (MyJsfAjaxTimeoutSetting)FacesUtil.getManagedBean("MyJsfAjaxTimeoutSetting");
  FacesContext fc = FacesContext.getCurrentInstance();
  RequestContext rc = RequestContext.getCurrentInstance();
  ExternalContext ec = fc.getExternalContext();
  HttpServletResponse response = (HttpServletResponse) ec.getResponse();
  HttpServletRequest request = (HttpServletRequest) ec.getRequest();
         
  if (timeoutSetting ==null) {
   System.out.println("JSF Ajax Timeout Setting is not configured. Do Nothing!");
   return ;
  }
 
   
  UserCredential user = SecurityUtil.getUserCredential();
  /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  //
  // You can replace the above line of code with the security control of your application.
  // For example , you may get the authenticated user object from session or threadlocal storage. It depends on your design.
  //
  /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  
  if (user==null) {
   // user credential not found.
   // considered to be a Timeout case
      
 
   if (ec.isResponseCommitted()) {
    // redirect is not possible
    return;
   }
       
   try{
        
       if (
     ( (rc!=null &&  RequestContext.getCurrentInstance().isAjaxRequest())
     || (fc!=null && fc.getPartialViewContext().isPartialRequest()))
      && fc.getResponseWriter() == null
       && fc.getRenderKit() == null) {
 
        response.setCharacterEncoding(request.getCharacterEncoding());
   
        RenderKitFactory factory = (RenderKitFactory) 
     FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);
   
        RenderKit renderKit = factory.getRenderKit(fc,
     fc.getApplication().getViewHandler().calculateRenderKitId(fc));
   
        ResponseWriter responseWriter =
     renderKit.createResponseWriter(
     response.getWriter(), null, request.getCharacterEncoding());
     fc.setResponseWriter(responseWriter);
      
        ec.redirect(ec.getRequestContextPath() +
          (timeoutSetting.getTimeoutUrl() != null ? timeoutSetting.getTimeoutUrl() : ""));    
       }
         
   } catch (IOException e) {
    System.out.println("Redirect to the specified page '" +
      timeoutSetting.getTimeoutUrl() + "' failed");
    throw new FacesException(e);
   }
  } else {
   return ; //This is not a timeout case . Do nothing !
  }
 }
 
 public PhaseId getPhaseId()
 {
  return PhaseId.RESTORE_VIEW;
 }
 
}

The details of the FacesUtil.getManagedBean("MyJsfAjaxTimeoutSetting") is shown below:

public static Object getManagedBean(String beanName) {
      
     FacesContext fc = FacesContext.getCurrentInstance();
     ELContext elc = fc.getELContext();
     ExpressionFactory ef = fc.getApplication().getExpressionFactory();
     ValueExpression ve = ef.createValueExpression(elc, getJsfEl(beanName), Object.class);
     return ve.getValue(elc);
}

Configuration
As said before, the purpose of the session scoped managed bean, MyJsfAjaxTimeoutSetting, is just to allow you to make the timeoutUrl configurable in your faces-config.xml.

<managed-bean>
 <managed-bean-name>MyJsfAjaxTimeoutSetting</managed-bean-name>
 <managed-bean-class>org.borislam.security.MyJsfAjaxTimeoutSetting</managed-bean-class>
 <managed-bean-scope>session</managed-bean-scope>
 <managed-property>
  <property-name>timeoutUrl</property-name>
  <value>/login.do</value>
 </managed-property>
</managed-bean>

Most importantly, add the PhaseListener in your faces-config.xml.

<lifecycle>
<phase-listener id="JSFAjaxTimeoutPhaseListener">hk.edu.hkeaa.infrastructure.security.JSFAjaxTimeoutPhaseListener</phase-listener>
</lifecycle>

If you are using spring framework, you could managed the MyJsfAjaxTimeoutSetting in Spring with the help of SpringBeanFacesELResolver. Then, you can use the following configuration.

<bean id="MyJsfAjaxTimeoutSetting" class="org.borislam.security.MyJsfAjaxTimeoutSetting" scope="session">   
 <property name="timeoutUrl" value="/login.do">  
</property></bean>






AJAX Session (web analytics) Requests Timeout (computing) Spring Security Spring Framework

Published at DZone with permission of Boris Lam, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Select ChatGPT From SQL? You Bet!
  • Mr. Over, the Engineer [Comic]
  • How Observability Is Redefining Developer Roles
  • AWS Cloud Migration: Best Practices and Pitfalls to Avoid

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: