Java – is ThreadLocal better than HttpServletRequest setAttribute(“key”,“value”)?
The servlet specification (see my previous question) guarantees that the same thread will execute all filters and associated servlets In view of this, if there is an option to use ThreadLocal (assuming you clean it correctly), I think HttpServletRequest SetAttribute is of no use in passing data I think using ThreadLocal has two advantages: type safety and better performance, because there is no string key or mapping (except that it may enter the thread collection through (non string) thread ID)
Someone can confirm whether I am right, so I can continue to give up setAttribute?
Solution
It depends on the specific functional requirements
For example, JSF stores facescontext in ThreadLocal This gives you access to all JSF artifacts, including "raw" HttpServletRequest and httpservletresponse anywhere in the code executed by facesservlet, such as managed bean Most other Java - based MVC frameworks follow the same example
According to your comments,
As for my assumption that this is a user example of session properties, I prefer to use the same method as JSF Create ThreadLocal < context > context is your custom wrapper class, which contains a reference to the current HttpServletRequest or httpservletresponse, so that you can access them anywhere in the code If necessary, you can directly provide convenient methods from the context class to obtain users
As for the entitymanager example, you can follow the same method, but I personally will not put it in the same ThreadLocal < context >, but a different method Or, better yet, simply get it from JNDI in the service layer, which will allow you to have more granular control over transactions In any case, please make sure you handle the submit / close correctly Taking over persistence and transaction management from containers should be very careful I really reconsider my aversion to using existing and well-designed APIs / frameworks (such as EJB / JPA), otherwise you will risk completely wasting time reinventing all standardized APIs and things
You can also see:
> Retrieving Web Session from a POJO Outside the Web Container > Design Patterns web based applications