Sessions

Terence Parr

HttpSession is useful for handling persisted data for each user within a session. According to HttpSession:

"Provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user...The session persists for a specified time period, across more than one connection or page request from the user."

Uses cookies to maintain state usually. Resin manages session HttpSession objects for you. You just have to ask for it. You can also invalidate a session if you want to log out a user.

Here is the key bit of code:

// get session object for this session or create if new
HttpSession session = request.getSession();

Use putValue(key,value) to save object/value (I think it's setAttribute() now actually).

Just use one and store all variables in there rather than multiple session variables.

Here are my typical session variables

    /** Session variable pointing to a user object */
    public static final String SESSION_MEMBER = "user";

    /** Indicates currently logged in (could be just visiting site) */
    public static final String SESSION_LOGGEDIN = "loggedin";

Here is how you can "log in" a user:

public void login(HttpSession session, User user) {
    session.putValue(SESSION_LOGGEDIN, "true");
    session.putValue(SESSION_MEMBER, user);
}

and logout:

public void logout(HttpSession session) {
    session.removeValue(SESSION_LOGGEDIN);
    session.removeValue(SESSION_MEMBER);
    session.invalidate();
}

Here is an example Login page and simple pagecount page.