In Java, a session is a way of keeping track of different activities across multiple requests between a client and a server. A session starts when the user requests for the first page and ends if the user hasn’t requested any pages for a given amount of time (timeout) . The time interval in which two systems communicate with each other can be termed as a session. Since HTTP and web servers are both stateless, the only way to maintain the state of the user is by making use of technologies that implement session tracking. Session tracking in servlets can be implemented by a number of methods, such as cookies, HttpSession API, URL rewriting, etc. .
To use a session in Java, first create a session using the getSession()
method of the HttpServletRequest
class. If the session already exists, the getSession()
method returns the valid session object associated with the request, identified in the session cookie that is encapsulated in the request object. Calling the method with no arguments creates a session if one does not exist that is associated with the request. Additionally, calling the method with a Boolean argument creates a session only if the argument is true. Once the session is established, examine and set its properties using the provided methods.
Some of the most important Servlet HttpSession methods include getId()
, which returns a unique session identifier (id) with a type String, and invalidate()
, which destroys a session object.