The JSP Files (part 6): State Of Grace - Session Dissection (
Page 8 of 9 )
Creating a JSP session is much simpler than writing a cookie. To
demonstrate this, here's the session equivalent of the cookie-based counter
you saw a few pages back.
<html>
<head>
</head>
<body>
<%
// 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);
session.putValue("counter", visits);
out.println("Welcome, stranger!");
}
else
{
// else increment and write the new value
visits = new Integer(visits.intValue() + 1);
session.putValue("counter", visits);
out.println("You have visited this page " + visits + " time(s)! Don't you
have anything else to do, you bum?! ");
}
%>
</body>
</html>
There isn't much you have to do to create a session - simply use the
putValue() method of the Session object to create one or more session
variable, and JSP will automatically create a session and register the
variables. You can then use the getValue() method to retrieve the values of
the session variables automatically.
An important point to be noted here is that it is necessary to typecast the
session variable while using getValue() - in the example above, we've
specifically stated the type of the variable in parentheses before
assigning it to a regular JSP variable. Since JSP allows you to bind
objects to the session, you can bind an Integer object and thereby bypass
some of the string-to-number conversion routines in the equvalent cookie
example.
With this information in mind, the example above becomes much simpler to
read. An "if" statement is used to take care of the two possible
alternatives: a first-time visitor (no prior session) or a returning
visitor (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 for
someSeconds 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, in
seconds, as an offset from midnight January 1 1970