Is ThreadLocal preferable for HttpServletRequest.setAttribute ("key", "value")?
Depends on the specific functional requirement.
JSF, for example, stores the FacesContext
in ThreadLocal
. This allows you to access all JSF artifacts, including the raw HttpServletRequest
and HttpServletResponse
anywhere in the code that FacesServlet
, such as managed beans. Most other Java-based MVC environments follow the same example.
According to your comment,
I need to transfer User and EntityManager objects from user and Filters databases to Servlet. I also found that they are often and unexpectedly needed in the code further down the line, and I am tempted to use them much higher than the Servlet (that is, in the embedded code called by doGet). I feel there might be a better way for deeper codes - suggestions?
Regarding the User
example, for which I assume this is a session attribute, I would prefer to follow the same approach as JSF. Create a ThreadLocal<Context>
, where Context
is your own wrapper class that contains references to the current HttpServletRequest
and possibly also HttpServletResponse
so that you can access them anywhere in your code. If necessary, use convenient methods to get, among others, the User
directly from the Context
class.
As for the EntityManager
example, you can follow the same approach, but I personally did not put it in the same ThreadLocal<Context>
, but rather a different one. Or, better, just get it from JNDI at the service level, which will allow you to more finely control transactions. In any case, please make sure that you are committing / closing correctly. Assuming persistence and managing transactions from the container should be carried out with extreme caution. I would really redefine the aversion to using existing and well-designed APIs / frameworks such as EJB / JPA, otherwise you risk spending a lot of time rethinking all the already standardized APIs and products.
See also: