IntroductionI 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
HttpSessionobject. This has given rise to an idea that I could wrap a standard
HttpSessionobject with a decorator similar to
HttpServletRequestWrapperand perhaps a implementation of the old session mechanism.
Currently there is no HttpSessionWrapper like
HttpServletResponseWrapperso 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.
ImplementationImplementation 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
HttpSessionis created from the
HttpServletRequestobject. This important fact can help determine how to implement our HttpSessionWrapper. I think that the easiest mechanism is to use an
@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.xmlfile 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
HttpServletRequestWrapperwith its modified
getSession()methods that return my HttpSessionWrapper. The HttpSessionWrapper can be downloaded here: session-wrapper
CodeThe code below includes the
HttpSessionWrapperand an example implementation of how to use it.
HttpSessionWrappercan 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.