For each servlet request I get, I pass, perhaps, 10 methods before I am at where I need to check something in the session and I need the HttpSession.
The only way I can get the HttpSession is from the HttpServletRequest, correct?
How do I keep track of the session for each servlet request? Unfortuantly I cannot simple make a singleton (ex, SessionInformation.instance().getAttribute(“name”)) because that session would then be used over all requests.
Is there a way to store the session globally for each request without having to pass it (or it’s information) down all the methods just in case I need it?
Update 1:
Alohci pushed me into the right direction. I need something that can either:
1) Manage to store variables globally only over a Thread. A “Singleton-per-Thread” solution?
2) Or is there a unique id for each thread/request a servlet gets? If so, what?
The server identifies its users by marking them through a cookie that holds a session ID on their browsers. On the server the session is where you place data that you need to keep track of during the client/server interaction (to give state to the application).
You can then grab the session out of a HttpServletRequest by doing
see javadoc: here
After you retrieve the session inside your servlet, you use
session.getAttribute("name")to retrieve whatever data you were interested in to keep track of the interaction.Why store it globally when the only thing that has the ID to access the session is the servlet that got a request that came with that session ID. Not everything in your application needs to know about every request.
Here is an example of a request that comes with a session ID cookie:
You can’t store this information globally, it is unique to each request.
When doing useful things with the data, don’t pass the session to your methods, pass the useful information, like user name, shopping cart content etc.
Your business logic methods shouldn’t even know what a session is. It’s more like an artefact.