Products Docs & Support Community

>> More Visual Web Pack Documentation

Redirection When Session Times Out

May [Revision number: V5.5.1-1]    

Security is an important consideration with all web applications. One security issue that you may need to implement concerns limiting user access to particular pages of a web application when variables are out of session scope. When this occurs, you might want to require the user to login again before proceeding.

Contents

Overview
Create a Project With Two Pages
  Using a Servlet Filter
Modifying the Button Action Handler Method
Summary
 


This tech tip works with the following technologies and resources

NetBeans IDE 6.0, 5.5.1, and 5.5  
JavaServer Faces Components/
Java EE Platform
works with1.2 with Java EE 5*
works with1.1 with J2EE 1.4
Travel Database requiredNot r equired
BluePrints AJAX Component Library not requiredNot required

* As of the date this tech tip was published, only the Sun Java System Application Server supported Java EE 5.

This tech tip has been tailored for use with the Sun Java Application Server PE 9.0 Update Release 1 and with Tomcat 5.5.17. If you are using a different server, consult the Release Notes and FAQs for known problems and workarounds. For detailed information about the supported servers and Java EE platform, see the Release Notes.

Overview

This tech tip explains how, when the session expires or goes to a null value, you can redirect the user to another page. In this situation, you want to execute the redirection when the page loads. Using a hyperlink does not work, nor does the standard code for a button's action handler method.

The most reliable way to handle this situation is to use a Servlet Filter. Using a Servlet Filter is also more efficient, since you set up the filter once and can use it from any page or component in the project. While you can also write custom code for a button action handler method, that latter approach is not as reliable because it depends on settings in the web.xml file. The modified action handler code must also be included on all pages from which you want to test for session timeout. Although this tip shows how to modify the button action handler, it is recommended that you use the Servlet Filter approach if at all possible.

Regardless of which method you choose, for the code to work you also need to set a session timeout value in the web.xml file; for example, set the session timeout value to one minute:
 <session-config>
       <session-timeout>1</session-timeout>
 </session-config> 

Create a Project With Two Pages

You can easily create this example yourself. Set up two pages in your Visual Web application: a Page1 that has a button and an ErrorPage that displays a session timeout message. If the user clicks the button on Page1 before the timeout value set in the web.xml file is reached, then nothing happens (because the session has not timed out). However, if the timeout value has been reached, indicating that the session has timed out, then the button should take the user to the ErrorPage.

Remember that, to see if redirection works when the session times out, you must wait more than whatever timeout value you have set in the web.xml file before clicking the button.

Using a Servlet Filter

The best way to redirect a user when a session times out is to use a Servlet Filter. Using this approach, you do not need to make any code modifications to a button’s action handler.

The general steps are:

  • Use the GUI to create a Filter class and set its filter mapping to Servlet and Faces Servlet.
  • Replace the code in the Servlet Filter class with custom code.
  • Deploy the project.

Here’s how to accomplish this.

  1. First, create the Filter class. In NetBeans 6.0, right click the project and click New -> Other to open the Choose File Type dialog. (In NetBeans 5.5 or 5.5.1, right click the project and click New->File/Folder to open the same dialog.) Then, in the dialog screen select Web in the Categories column (if it is not already highlighted) and Filter in the Files Type column. Click Next.
  2. The New Filter dialog displays. Enter SessionCheckFilter for the Class Name and click Next. (You can use any name you want for the filter.)
  3. In the Configure Filter Deployment dialog, select SessionCheckFilter in the Filter Mappings box, if not already highlighted, then click Edit.
  4. Figure 1. Configure Filter Deployment Dialog (click to enlarge image)

  5. In the Filter Mapping dialog, check Servlet and be sure it is set to Faces Servlet. Click Finish.
  6. Figure 2: Filter Mapping Dialog
  7. Now, open the SessionCheckFilter class in the source editor and replace the entire class with the following code.
Code Sample 1: SessionCheckFilter Code for Redirection
public class SessionCheckFilter implements Filter {
 private static int firstRequest = 0;
 public void doFilter(ServletRequest request, ServletResponse response,
                    FilterChain chain) throws IOException, ServletException {
      HttpServletRequest hreq = (HttpServletRequest)request;
      HttpServletResponse hres = (HttpServletResponse)response;
HttpSession session = hreq.getSession(); if (session.isNew()) { if(firstRequest == 0){ firstRequest++; } else { hres.sendRedirect("faces/ErrorPage.jsp"); return; } } chain.doFilter(request, response); } public void init(FilterConfig filterConfig) throws ServletException {}
public void destroy() {} }

The Servlet Filter does all its processing in the doFilter method. It gets a reference to the session and tests if the session is new or if the user is still in the previous session. If new, the code increments the variable firstRequest, indicating this is no longer a new session. But if the user is still within the same session and it has timed out; the Servlet Filter redirects the user to a page set up to handle time out situations. In this example, it is faces/ErrorPage.jsp.

Now, you can simply deploy and run the project. The filter redirects you to the error page when you wait more than the timeout value (in our case, one minute) before clicking the button on the main page. This redirection occurs regardless of how many times you may have previously clicked the button. Note, too, that the Servlet Filter works for any page and any component. There is no need for you to write any special code for the components on a page.

Modifying the Button Action Handler Method

You can instead write some custom code for the button action handler method to redirect the user to another page when a session expires.

In addition to setting a timeout value, for this approach to work be sure that the javax.faces.STATE_SAVING_METHOD parameter in the web.xml file is set to client. If set to server, then the button action method will never be called, regardless of the timeout setting. To verify and change the setting for this parameter, expand the web.xml file Context Parameters section. If the value for javax.faces.STATE_SAVING_METHOD is set to server, use the Edit button to change the property value to client.

Figure 3: Setting javax.faces.STATE_SAVING_METHOD parameter

All the critical code is in the button’s action handler method. Open the Page1 button action handler method in the Java source editor and add the following code to the method. After entering this code, use the Fix Imports function to import the classes used by the code.

Code Sample 2: Button Action Handler for Session Timeout Redirection
 public String button1_action() {
        ExternalContext externalContext = getFacesContext().getExternalContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
        HttpSession session = request.getSession();
        if (session.isNew()) {
          try {
            String errorPageURL = externalContext.getRequestContextPath() +
                "/faces/ErrorPage.jsp";
            externalContext.redirect(errorPageURL);
          } catch(IOException ioe) {
            System.out.println("==============");
            ioe.printStackTrace(System.out);
            System.out.println(ioe.toString());
            System.out.println("==============");
          }
        } else {
          System.out.println("==============");
          System.out.println("*** Session is not New ***");
          System.out.println("==============");
        }
     return null;
}

The key parts to the action handler method are at the beginning. The first three methods:

 ExternalContext externalContext = getFacesContext().getExternalContext();
 HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
 HttpSession session = request.getSession();

give you a handle to the session itself.

Next, you test if the session is new or if the user is still in the same (previous) session. If new, then the code within the try block executes; otherwise, the user is still within the same session and the action handler method returns. The redirection code is within the try block:

 if (session.isNew()) {
   try {
     String errorPageURL = externalContext.getRequestContextPath() +
        "/faces/ErrorPage.jsp";
   externalContext.redirect(errorPageURL);

The above code establishes the path to the page you want redirection to go to, which in this case is the error page, ErrorPage.jsp. That path is a combination of the web application context and the name of the page that redirection goes to. The code uses the ExternalContext.getRequestContextPath method to return the portion of the request URI that identifies the request's web application context, and it appends the name of the redirection page (/faces/ErrorPage.jsp) to the context.

Then, call the ExternalContext redirect method, passing it the absolute URL path to the redirection page. The redirect method redirects a client request to the specified URL. It also invokes the responseComplete method on the current request's FacesContext instance.

Summary

While both approaches work, it’s easy to see that using a Servlet Filter is the more straightforward approach for handling redirection when a session times out. Not only can you use the IDE dialogs to create the Servlet Filter, the code you need to add is uncomplicated. Using a Servlet Filter also avoids the need to have the redirection logic on each page (or included within multiple component action handlers) for which you want to check for a session time out.


This page was last modified:  May 24,