Home

This Chapter
-Chapter 20: Early HttpSession Invalidation
-HttpSession Invalidation in Struts
-Early HttpSession Invalidation
-Summary

Table of Contents
-Introduction
-Chapter 1: Model 2 and Struts
-Chapter 2: Input Validation with Action Forms
-Chapter 3: The HTML Tag Library
-Chapter 4: Input Validation and Data Conversion
-Chapter 5: The Validator Plugin
-Chapter 6: The Expression Language
-Chapter 7: JSTL
-Chapter 8: The Bean Tag Library
-Chapter 9: The Logic Tag Library
-Chapter 10: Struts-EL, Nested, selectLabel
-Chapter 11: Message Handling and Internationalization
-Chapter 12: The Tiles Framework
-Chapter 13: Securing Struts Applications
-Chapter 14: The Config Object
-Chapter 15: The Persistence Layer
-Chapter 16: Object Caching
-Chapter 17: File Upload and File Download
-Chapter 18: Paging and Sorting
-Chapter 19: Preventing Double Submits
-Chapter 20: Early HttpSession Invalidation
-Chapter 21: Decorating Request Objects
-Chapter 22: How Struts Works

Previous
Next

 

HttpSession Invalidation in Struts

Destroying an HttpSession object in a Struts application is not as simple as calling the invalidate method on the HttpSession object. This is because even a simple forward to a JSP will create a new HttpSession object.

Let’s begin by reviewing some facts.

By default, every action invocation in Struts is guaranteed to create an HttpSession object, if there is none already for the user, even if the processing has not instantiated an action class yet (in the case of an action form failing to validate). This is because Struts needs to store the user’s locale information in an HttpSession object. (For those interested, check the process and processLocale methods in the org.apache.struts.action.RequestProcessor class). Therefore, there is also no point in using the directive <%@ page session=”false”%> in a JSP if the JSP is a forward destination of a Struts action.

Then, how do you destroy an HttpSession object? By calling invalidate on the HttpSession object and prevent Struts from creating a new HttpSession instance.

To destroy an HttpSession object, you can create an action object and calls the invalidate method on the HttpSession object.

public ActionForward execute(ActionMapping mapping,
  ActionForm form, ServletRequest request,
  ServletResponse response) throws Exception {
  // no need to check if HttpSession from the getSession is
  // null, because it will not be null.
  request.getSession(false).invalidate();
  ...
}

However, note that the ActionMapping class’s findMapping method, the method you normally call at the end of your action class, causes an HttpSession instance to be created. Therefore, you must avoid using it after invalidating an HttpSession object. Instead, you can either return null or use response.sendRedirect method to redirect method to an HTML or JSP. If you must choose the latter, do not redirect to another Struts action as this will create another HttpSession object.

Previous
Next