Accessing and Manipulating the Session Object
Use
This procedure refers to retrieving the session object that is associated with the current request (or creating one if no such object exists) and reading attributes that are set in the session object.
Procedure
You can access an HttpSession object in the service method of your servlet. Proceed as follows:
-
Use the request.getSession() method of the HttpServletRequest object. If a session object is already associated with the client request, this method returns it. If no such object exists on the server, it creates one for that client.
If you do not want to create a new session if one does not exist on the server for that client, you can use the request.getSession(false) method.
Some applications may need to know if the session is currently established and forward the client to a welcome or a login page (so that the client is aware that a new session is established on the server). You can run this check in your servlet using the HttpSession.isNew() method. If it returns true , the session is new and the client does not yet know about it.
-
Use the getAttribute(String name) or getAttributesNames() methods of the HttpSession object to retrieve attributes that are associated with it. If you want to set a new attribute, or remove an existing one, use setAttribute() and removeAttribute() , respectively. Information that is stored into the session object appears as name-value pairs.