Persistence with The Session Object

HTTP is a 'connectionless' protocol. However, it is sometimes advantagous to keep track of a user as he goes from page to page using the browser. J2EE defines a 'session' as the unique relationship between a specific browser and a specific Web Application. The JSP or Servlet handling the user can store objects in what is called a Session object (actually javax.servlet.HttpSession), and retrieve them in later Servlets and/or JSP's as long as it is for the same browser and Web Application.

A Session object is very similar to a Hash table, in that objects are stored and retrieved by using a String 'key'. The method to store the object is setAttribute() and the one method that retrieves the object is getAttribute(). Here is a Servlet that shows how the Session object is obtained and used.

   import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
   public class Sess extends HttpServlet {
public void service (HttpServletRequest req , HttpServletResponse res)
throws IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
HttpSession session = req.getSession(true); //create Session if none
if (session.getAttribute("Number") == null){
Integer i = new Integer(0);
session.setAttribute("Number",i);
}
Integer i = (Integer)session.getAttribute("Number");
int i2 = i.intValue();
i2 = i2+1;
i = new Integer(i2);
session.setAttribute("Number",i);
out.println("Value of incrementing number is " + i + "<BR>");
String id = session.getId();
out.println("Session ID = " + id + "<BR>");
}
}

Here is a JSP page that does the same thing:

<%
if (session.getAttribute("Number") == null){
Integer i = new Integer(0);
session.setAttribute("Number",i);
}
Integer i = (Integer)session.getAttribute("Number");
int i2 = i.intValue();
i2 = i2+1;
i = new Integer(i2);
session.setAttribute("Number",i);
out.println("Value of incrementing number is " + i + "<BR>");
String id = session.getId();
out.println("Session ID = " + id + "<BR>");
%>

What appears in the browser the following, with the number incremented everytime the page is refreshed:

Value of incrementing number is 2
Session ID = 16691068743363033

In Jrun, the actual session information is kept in a cookie on the user's machine that is running the browser. If the Jrun server goes down, then the Jrun server tries to 'persist' the session information in a server file. The default location for this session information is WEB-INF/sessions.