- Container creates a session id for each user.
- The container uses this id to identify the particular user.
An object of HttpSession can be used to perform two tasks:
- bind objects
- view and manipulate information about a session, such as the session identifier, creation time, and last accessed time.
The HttpServletRequest interface provides two methods to get the object of HttpSession:
- If the session already exist, it will return existing session else create a new session
- If create is true, Always returns a new session.
- If create is false returns a existing session.
Commonly used methods of HttpSession interface:
- public String getId():Returns a string containing the unique identifier value.
- public long getCreationTime():Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.
- public long getLastAccessedTime():Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT.
- public void invalidate():Invalidates this session then unbinds any objects bound to it
HttpSession session = request.getSession(); // If the session already exist,
it will return existing session else create a new session
HttpSession session = request.getSession(true); //Always returns a new session
session.setAttribute("uname","Bharath");
Getting Existing Session
HttpSession session = request.getSession(false); //Always returns existing session
String name = (String)session.getAttribute("uname");
Destroying a Session
session.invalidate();