Now that you've mastered the basics, it's time to bring out thebig iron. This week, The JSP Files explores the various techniquesavailable to "maintain state" on a JSP-based Web site. Learn about theCookie and Session objects, find out how to build a cookie-based hitcounter, and read about a simple yet effective way of protecting sensitiveWeb pages with the Session object.
Creating a JSP session is much simpler than writing a cookie. Todemonstrate this, here's the session equivalent of the cookie-based counteryou saw a few pages back.
// get the value of the session variable
Integer visits = (Integer)session.getValue("counter");
// if null
if (visits == null)
// set it to 0 and print a welcome message
visits = new Integer(0);
// else increment and write the new value
visits = new Integer(visits.intValue() + 1);
out.println("You have visited this page " + visits + " time(s)! Don't you
have anything else to do, you bum?! ");
There isn't much you have to do to create a session - simply use theputValue() method of the Session object to create one or more sessionvariable, and JSP will automatically create a session and register thevariables. You can then use the getValue() method to retrieve the values ofthe session variables automatically.
An important point to be noted here is that it is necessary to typecast thesession variable while using getValue() - in the example above, we'vespecifically stated the type of the variable in parentheses beforeassigning it to a regular JSP variable. Since JSP allows you to bindobjects to the session, you can bind an Integer object and thereby bypasssome of the string-to-number conversion routines in the equvalent cookieexample.
With this information in mind, the example above becomes much simpler toread. An "if" statement is used to take care of the two possiblealternatives: a first-time visitor (no prior session) or a returningvisitor (pre-existing session). Depending on whether or not the "counter"variable exists, appropriate action is taken.
The Session object also comes with a bunch of other interesting methods -here are some of them:
getId() - returns a string containing the unique session ID
setMaxInactiveInterval(someSeconds) - keeps the session active forsomeSeconds duration after the last client request
invalidate() - destroy the session
getAttribute() and setAttribute() - try these is getValue() and putValue()don't work
getCreationTime() - returns the time at which this session was created, inseconds, as an offset from midnight January 1 1970