Servlet Session Tracking

Servlet provides session tracking using HttpSession API. To use sessions in servlet you need to follow some basic steps. These steps are given below.

  1. First we access the session object which is associated with the current request.
    HttpSession session = request.getSession();
    We can get the HttpSession object by calling getSession() method of HttpServletRequest.
  2. Then we fetch the data associated with a session. HttpSession objects are stored on the server. Session objects store data in a form of key value pair in a hash table.
    String value = (String)session.getAttribute("key");
  3. After that we store the information in session object by accessing setAttribute() method. To set the key-value pair use the code snippet given below.
    session.setAttribute("key", "value");
  4. Finally we can delete the session data. We can remove a key-value pair from session object or we can delete the whole session object.
    Remove a key-value pair
    Discard the session object
    You can discard the session object by calling invalidate. It clears any object which is bound to session.

HttpSession getAttribute, setAttribute and invalidate session.