Session Management


Introduction

Session management is the process of keeping track of the activities of a user across Web pages.
Consider an example of an online shopping website.

The user can choose a product and add it to the shopping cart.
When the user moves to a different page, the details in the shopping cart are still retained so that the user can check the items in the shopping cart and then place the order.
HTTP is a stateless protocol and therefore cannot store the information about the user activities across Web pages.
However, there are certain techniques that helps to store the user information across Web pages using HTTP protocol.
The techniques that you can use to maintain the session information are:
1. Hidden form field
2. URL rewriting
3. Cookies
4. Servlet session API


Servlet Session API

You can use the classes and interfaces defined in the Servlet Session API to create and manage user sessions.
Various interfaces provided by the Servlet Session API to create and manage user session are:
a) javax.servlet.http.httpSession
b) javax.servlet.http.HttpSessionListener
c) javax.servlet.http.HttpSessionBindingListener


Behaviour of Session object:

The javax.servlet.http.HttpSession interface provides methods for tracking the session of a user.
You can create an object of HttpSession interface to store session information as name/value pairs.
You can later retrieve this information to manage user sessions.

The following describes the various methods defined in the HttpSession interface:
1. public void setAttribute (String name, Object value)
Binds an attribute to a session object with a unique name and stores the name/value pair in the current session. If an object is already bound with the same attribute, then the new object replaces the existing.

2. public getAttribute(String name)
Retrieves the object bound with the attribute name specified in the method , from the session object. If no object is found for the specified attribute, then the getAttribute() method returns null.

3. public Enumeration getAttributeNames()
Returns the name of all the objects that are bound to the session object.

4. public void removeAttribute(String name)
Unbinds the session object from the attribute , name specified in the method.

5. public void setMaxInactiveInterval(int interval)
Sets the maximum time for which the session will remain active. The time is specified in seconds. If there is no client request during this time ,
then the server invalidates the session. A negative value in this method signifies that the session should always remain active.

6. public int getMaxInactiveInterval()
Returns the maximum time in seconds for which the server will not invalidate the session even if there is no client request.

7. public String getId()
Returns a string that contains the unique identifier associated with the session.

8. public void invalidate()
Invalidates a session. All the objects bound to the session are automatically unbound.