| This Chapter | |
| - | Chapter 20: Early HttpSession Invalidation |
| - | HttpSession Invalidation in Struts |
| - | Early HttpSession Invalidation |
| - | Summary |
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.