Accessing HttpContext, HttpServletRequest and HttpServletResponse from any place in the code
What I want is to access current HttpServlerRequest + HttpServletResponse + HttpSession + some other important inforamation like user data and user's preferences from any point in my application. At the moment I am creating a special object MyServletContext which is then passed as the first parameter to all methods of all my objects. I want to get rid of this parameter but I am not sure what is the best way to do it.
One of my ideas is to create a global cache where I store MySer开发者_运维百科vletContext hashed by the current thread. Whenever I need any information stored in MyServletContext I will call this cache which will find me the right object. I know I will need to make this cache thread safe and I know how to do it. The question is: is there any better way to do it?
I used to use ThreadLocal for this purpose. Create HttpFilter that puts HttpRequest into ThreadLocal and use it everywhere in your code.
Using ThreadLocal
is a typical way to achieve this, but it is indeed not a good option.
Passing a whole context everywhere is also not preferable.
The best thing to do it pass as parameters only the data that is needed. Thus you are not making your service layer dependent on the web layer. And it is more testable.
精彩评论