[ Team LiB ] Previous Section Next Section

Forcing a New Session

When you call the getSession method to retrieve the current session, the request object automatically creates a session if one doesn't already exist. In some JSP implementations, the session is created automatically even if you never use it. Most of the time, you don't really care when the session has been created. Other times, however, you need to explicitly reset the existing session and start over.

Suppose, for example, that you have implemented an online shopping site. A user logs on, visits a few pages, and selects several items to buy. You store these items in the user's session as she travels from page to page. Now, suppose the user decides that she doesn't want any of those items, and rather than go through the trouble of removing them from her shopping cart, she decides to just log in to your site again.

If a user comes back into your login page, you probably want to start her over with a clean slate. Although you can design a site that is smart enough to figure out what the user was last doing and send her back to where she left off, most people assume that when they come in through the "front door" they are starting over.

Security and Sessions

graphics/didyouknow_icon.gif

There's a good reason to start a session over when entering through the login page. A user might walk away from the computer while at the login screen, thinking his order is now gone. Imagine his surprise if another user could walk up to the computer, log in, and have access to his order, complete with his credit card number. For this reason, you should either clear the session or associate it with a user.


The getSession method in the request object enables you to control the creation of new sessions. When you ask for a session, you can ask that the request object not create a new session if one doesn't already exist. The following segment of code automatically invalidates the previous session and then creates a new one:


// Get the old session, but don't create a session if
// one didn't already exist (passing true would allow
// creation of a new one).
    HttpSession oldSess = request.getSession(false);

// If there was an old session, invalidate it.
    if (oldSess != null)
    {
        oldSess.invalidate();
    }

// Now create a fresh new session.
    HttpSession session = request.getSession(true);

This code works for both JSP and servlets, except that you shouldn't re-declare a session for a JSP. Instead, the last line should just read


session = request.getSession(true);
    [ Team LiB ] Previous Section Next Section