Introducing the Session API

The Session API is a subset of the Java Servlet framework. It centres around the HttpSession object, which on the Servlet represents the "session of the client whose request is being processed". To obtain or create a session, we call HttpServletRequest.getSession(). For example:

public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {

  // get current session, or initialise one if none
  HttpSession sess = req.getSession(true);
}

Note:

Session attributes

Sessions per se aren't terribly useful without session attributes. A session attribute is effectively a Java object that we associate with the session. For example, we can implement a "login request" as follows:

public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
  String username = req.getParameter("username");
  String password = req.getParameter("password");
  DBUser user = fetchFromDatabaseIfValid(username, password);
  HttpSession sess = req.getSession(true);
  sess.setAttribute("USER", user);
  if (user == null) {
    // send 'no user/password match' message
  } else {
    // send 'successful login' screen
  }
}

In this example, we assume that fetchFromDatabaseIfValid() returns an object of type DBUser, which encapsulates data about that user held on a database. We assume that this method returns null if either the user doesn't exist, or their password doesn't match the one provided. In either case, we associate the DBUser reference returned with the current session via a call to HttpSession.setAttribute(). (Note that this will have the subtle effect of clearing any current user from the session if an invalid login is entered.) The user is attached to the session by way of an attribute "key", which is typically a string of our choosing (USER in this case), though could actually be any Java object.

Reading session attributes

Once users are "logged in" using the above method, then on subsequent page accesses, we can check who (if any) is the "currently logged in" user by calling getAttribute() on the session. Again, we need to remember to synchronize. In this case, we may also prefer not to create a session unless necessary:

private DBUser getCurrentUser(HttpServletRequest req) {
  HttpSession sess = req.getSession(false);
  if (sess == null) return null;
  return (DBUser) sess.getAttribute("USER");
}

Invalidating a session completely

When you want to invalidate or "remove all traces" of a session from the server, make a call to HttpSession.invalidate().

private void doLogout(HttpServletRequest req) {
  HttpSession sess = req.getSession(false);
  if (sess != null) {
    sess.invalidate();
  }
}

Next

Having looked at the basics of the Session API, other considerations include: