Tims Servlet Tutorial

Tutorial Home

  1. What are servlets ?
  2. The Hello World Servlet
  3. Running Servlets
  4. Reading Form Data
  5. Servlet Configuration
  6. Client Side Form Validation
  7. Cookies
  8. Sessions
  9. Authentication
  10. Dynamic Images
  11. Design, Testing, Security
  12. Servlets and Apache
  13. Using Servlets in SOCS

Sessions


Cookies are a useful way of link small amounts of information to a specific user, but suppose your needs are more complicated ? eg, you have a form for data entry which is split over several pages, but you want all the information entered on the earlier pages to be 'stored' so that it can all be processed in one go. One common solution is to use HIDDEN input tags inside the later forms to store the selections from the earlier forms eg :

<FORM ACTION="/servlets/FirstServlet">
<INPUT TYPE="TEXT" NAME="data1">
<INPUT TYPE=SUBMIT VALUE=Submit>
</FORM>

When submitted, 'FirstServlet' would dynamically generate the form for the second stage of the process so that it includes the data from the first as part of the form :

<FORM ACTION="/servlets/SecondServlet">
<INPUT TYPE="HIDDEN" NAME="data1" VALUE="xxxxx">
<INPUT TYPE="TEXT" NAME="data2">
<INPUT TYPE=SUBMIT VALUE=Submit>
</FORM>

This method is very reliable, but can be cumbersome. A much more effective method is to use an HttpSession. Sessions allow you to associate Java objects with a given user of the website (usually identified by a cookie, but this is automatic, so you don't have to worry about it). The Session stores these objects using Strings as keys, in use this is very similar to a Hashtable.

The following Servlet picks up a parameter which the user has entered and stores it in a session. :

 public void doPost(HttpServletRequest req, HttpServletResponse res)
  throws ServletException, IOException
 {
  String name=req.getParameterValues("yourname")[0];

  //*****Get the current Session. The 'true' parameter tells
  //       Java to create a new one if there isn't one already*****
  HttpSession session=req.getSession(true);
  session.putValue("name", name);

  //*****Send the reply*****

  res.setContentType("text/html");
  PrintWriter out=res.getWriter();
  out.println("<HTML>\n"+
   "<HEAD><TITLE>Split Name Servlet Response</TITLE></HEAD>\n"+
   "<BODY>\n<CENTER><BR><B>\n"+
   "<P>Your name has been recorded in a session.</P>"+
   "\n</B></CENTER>\n"+
  </BODY>\n</HTML>" );
  out.close();
 }

The second Servlet will try to pick up a pre-existing session and extract the stored parameters from it. It will then clear the session from memory. You may not always want to do this, if you have many servlets that need to pick up the data in the session and you can safely leave sessions 'behind', the Servlet engine will automatically clear out any sessions which have been inactive for a certain length of time. However, if you have a Servlet which represents a definitive 'end point' after which the session is not needed, you should explicitly call the invalidate() method to clear the session.

 public void doPost(HttpServletRequest req, HttpServletResponse res)
  throws ServletException, IOException
 {
  //***Get the current session. 'false' parameter tells Java not to create a new***
  //***one if one does not exist, so returns null if there is no session***
  HttpSession session=req.getSession(false);
  String output="No Session";
  if (session!=null)
   output="Hello "+session.getValue("name");

  //*****Send the reply*****

  res.setContentType("text/html");
  PrintWriter out=res.getWriter();
  out.println("<HTML>\n"+
   "<HEAD><TITLE>Split Name Servlet Response</TITLE></HEAD>\n"+
   "<BODY>\n"+
   "<CENTER><BR><B>\n"+
   "<P>"+output+"</P>"+
   "\n</B></CENTER>\n"+
  </BODY>\n</HTML>" );
  out.close();

  //*****We've finished with the session, so clean it up*****
  session.invalidate()
 }

You can try out the sessions servlets below :

Please Enter your name

Click here to test session

<< Previous Page | Next Page >>




Tims Home Page       |       Page last modified : 19 May 2003