Monday, December 31, 2012

Creating and Implementing An HttpSessionWrapper


I am faced with a problem currently where I have an application that was written before the J2EE specification was written. The application has its own application server, session, and state management. I am in the process of modernizing this application and transforming it into a standard Java EE application. However, there is a lot of code over 1.5m LOC. That makes this process very intensive.

One of the issues I have been wrestling with is session management. As I previously noted, the application has its own session and state management mechanisms. The session object is not too vastly different from a standard HttpSession object. This has given rise to an idea that I could wrap a standard HttpSession object with a decorator similar to HttpServletRequestWrapper and perhaps a implementation of the old session mechanism.

Currently there is no HttpSessionWrapper like HttpServletRequestWrapper, or HttpServletResponseWrapper so I wrote my own. It was simple to do and I hope others who may need a HttpSessionWrapper will use it. Once I wrote the wrapper, implementing it was the harder part.


Implementation requires a little knowledge of how HTTP requests are handled by servlets, and request and response handling in general. The most important thing to remember is: the HttpSession is created from the HttpServletRequest object. This important fact can help determine how to implement our HttpSessionWrapper. I think that the easiest mechanism is to use an HttpServletRequestWrapper in a @WebFilter. Filters are the first items that a request will pass through to reach the servlet, and the last thing it will pass through in the response.

If you use this mechanism, for implementing your HttpSessionWrapper, you must ensure that this is the first filter that the request will pass through. If it is the only filter, that should be very easy to implement. If you are using multiple filters with annotations, you will need to use a web.xml file to place them in the order you want them applied.

The example code I have below takes advantage of the fact that I can use a filter and that once I pass in my HttpServletRequestWrapper with its modified getSession() methods that return my HttpSessionWrapper. The HttpSessionWrapper can be downloaded here: session-wrapper


The code below includes the HttpSessionWrapper and an example implementation of how to use it.


Implementing a HttpSessionWrapper can be done very easily with a little thought, and perhaps a good blog article on it. The session-wrapper and session-wrapper-example code is available on BitBucket as Mercurial projects.. The projects were developed using NetBeans 7.2.1 and Apache Maven and was tested using Glassfish 3.1.2.


Popular Posts