Thursday, July 5, 2018

HttpSession interface

  • 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:
  1. bind objects
  2. view and manipulate information about a session, such as the session identifier, creation time, and last accessed time.
Get the HttpSession object:

The HttpServletRequest interface provides two methods to get the object of HttpSession:


1. public HttpSession getSession(): 
  • If the session already exist, it will return existing session else create a new session
2. public HttpSession getSession(boolean create):
  •  If create is true, Always returns a new session.
  • If create is false returns a existing session.

Commonly used methods of HttpSession interface:


  1. public String getId():Returns a string containing the unique identifier value.
  2. public long getCreationTime():Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.
  3. 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.
  4. public void invalidate():Invalidates this session then unbinds any objects bound to it
Creating a New Session

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();

No comments:

Post a Comment