Wednesday, August 26, 2009

JSP Sessions

A session is an object associated with a visitor. Data can be put in the session and retrieved from it, much like a Hashtable. A different set of data is kept for each visitor to the site.

Here is a set of pages that put a user's name in the session, and display it elsewhere. Try out installing and using these.

<%
String name = request.getParameter( "username" );
session.setAttribute( "theName", name );
%>

<. HTML>
<. BODY>
<. A HREF="NextPage.jsp">Continue<. /A>
<. /BODY>
<. /HTML>

The SaveName.jsp saves the user's name in the session, and puts a link to another page, NextPage.jsp.

NextPage.jsp shows how to retrieve the saved name.

<. HTML>
<. BODY>
Hello, <%= session.getAttribute( "theName" ) %>
<. /BODY>
<. /HTML>

If you bring up two different browsers (not different windows of the same browser), or run two browsers from two different machines, you can put one name in one browser and another name in another browser, and both names will be kept track of.

The session is kept around until a timeout period. Then it is assumed the user is no longer visiting the site, and the session is discarded.