Original Pattern: ServletRequest in ThreadLocalAug 2, 2007 · 2 minute read · Comments
After seeing Scala had elements of Erlang through Actors, I decided to take a closer look at the language. There is an interesting new web framework in Scala, called Lift. One drawback of Lift is that it seems to be very cutting edge and not that easy to grasp. While reading its source code, I stumbled upon a strange pattern: Storing the ServletRequest in a ThreadLocal .
I had not seen that before, and was wondering why one would do such a thing. It seems to be unintuitive. I found my answer through… GWT widgets. In this page, the author explain motivations behind doing such a thing:
While not 100% in tune with the MVC pattern, it is often convenient to access the servlet
container, the HTTP session or the current HTTP request from the business layer. The GWT-SL
provides several strategies to achieve this which pose a compromise in the amount of configuration
required to set up and the class dependencies introduced to the business code.
The easiest way to obtain the current HTTP request is by using the
which provides convenience methods for accessing the
HttpServletResponseinstances. Please note that it makes use of thread local variables
and will obviously not return correct values if used in any other than the invoking thread.