How do I keep track of the session for
each servlet request?
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).
session.setAttribute("name", SerializableObject)
Note: Because App Engine stores session data in the datastore and memcache, all values stored in the session must implement the java.io.Serializable interface.
You can then grab the session out of a HttpServletRequest by doing
request.getSession()
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.
Is there a way to store the session globally for each request
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:
GET /something.htm HTTP/1.1
Accept: www/source
Accept: text/html
Cookie: sessid=123456789
You can't store this information globally, it is unique to each request.
Without having to pass it
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.
HttpSession session = request.getSession() //inside a servlet
String userName = session.getAttribute("name");
List<ShoppingItems> items= session.getAttribute("cart");
MakeTheUserPay(userName, items) //no session passing here
Your business logic methods shouldn't even know what a session is. It's more like an artefact.