Java, Programming

Session Management in Servlets

Previous : Maintaining Client State

Since there is no way for an HTTP client to signal that it no longer needs a session, each session has an associated timeout so that its resources can be reclaimed. The timeout period can be accessed with a session’s [get|set]MaxInactiveInterval methods. You can also set the timeout period in deploytool:

  1. Select the WAR.
  2. Select the General tab.
  3. Enter the timeout period in the Advanced box.

To ensure that an active session is not timed out, you should periodically access the session via service methods because this resets the session’s time-to-live counter.

When a particular client interaction is finished, you use the session’s invalidate method to invalidate a session on the server side and remove any session data.

The bookstore application’s ReceiptServlet is the last servlet to access a client’s session, so it has responsibility for invalidating the session:

public class ReceiptServlet extends HttpServlet {
   public void doPost(HttpServletRequest request,
               HttpServletResponse response)
               throws ServletException, IOException {
      // Get the user's session and shopping cart
      HttpSession session = request.getSession();
      // Payment received -- invalidate the session

Previous :  Session Tracking

Tagged , , , , , , , , , , , ,