Home > Articles > Programming > Java

  • Print
  • + Share This

Session Tracking with the Servlet API

The Servlet API has its own built-in support for session tracking. The HttpSession object provides this functionality. In this section, I focus on four of the HttpSession's session tracking methods.

The first method is the setAttribute() method. The setAttribute() method binds a name/value pair to store in the current session. If the name already exists in the session, it is replaced. The method signature for setAttribute() is listed as follows:

public void setAttribute(String name, Object value)

The next method is the getAttribute() method, which is used to get an object that is stored in the session. The getAttribute() method takes a string representing the name that the desired object is bound to. Its signature is listed as follows:

public Object getAttribute(String name)

The third session method returns an array of the current bound names stored in the session. This method is convenient if you want to remove all the current bindings in a session. Its signature is listed as follows:

public String[ ] getAttributeNames()

The last session method is the removeAttribute() method. As its name suggests, it removes a binding from the current session. It takes a string parameter representing the name associated with the binding. Its method signature is listed as follows:

public void removeAttribute(String name)

Now that I have discussed the HttpSession object, let's take a look at an example of how to use it. In this example, you will service a request that contains a list of movies to add to a user's account. You will then parse the submitted list, add it to the customer's session, and redisplay it for approval. When the customer approves the list, they will click the Proceed to Checkout button to commit the transaction. Listing 5.4 contains the source for this example.

Listing 5.4 HttpSessionServlet.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class HttpSessionServlet extends HttpServlet {

 public void init(ServletConfig config)
  throws ServletException {

  super.init(config);
 }

 //Process the HTTP Get request, this method
 // will handle the checkout
 public void doGet(HttpServletRequest request,
  HttpServletResponse response)
  throws ServletException, IOException {

  String[ ] movies = null;

  // Get a handle to the HttpSession Object
  // if there is no session create one
  HttpSession session = request.getSession(true);

  // Get the movies list object bound to the
  // name "Movies"
  if ( session != null ) {

   movies = (String[ ])session.getAttribute("Movies");
  }

  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  out.println("<html>");
  out.println("<head><title>Session Servlet</title></head>");
  out.println("<body>");

  // Iterate over the movies array, displaying the
  // current list of movies stored in the session
  out.println("<H2>Thank you for purchasing:</H2>");
  for ( int x = 0; x < movies.length; x++ ) {

   out.println(movies[x] + "<BR>");
  }
  out.println("</body></html>");
  out.close();
 }

 //Process the HTTP Post request
 public void doPost(HttpServletRequest request,
  HttpServletResponse response)
  throws ServletException, IOException {

  // Parse the movies selected
  String movies[ ] = request.getParameterValues("Movies");

  // Get a handle to the HttpSession Object
  // if there is no session create one
  HttpSession session = request.getSession(true);

  // add the list of movies to the session
  // binding it to the String "Movies"
  if ( session != null ) {

   session.setAttribute("Movies", movies);
  }

  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  out.println("<html>");
  out.println("<head><title>Session Servlet</title></head>");
  out.println("<body>");

  out.println("<H2>Contents of Shopping Cart</H2>");

  // Display the submitted movie array
  for ( int x = 0; x < movies.length; x++ ) {

   out.println(movies[x] + "<BR>");
  }
  // Create a form to submit an order
  out.println("<FORM action=/djs/servlet/HttpSessionServlet " +
   "METHOD=GET>");
  out.println("<input type=\"Submit\" name=\"add\" value=" +
   "\"Proceed to Checkout\"></FORM>");

  out.println("</body></html>");
  out.close();
 }

 //Get Servlet information
 public String getServletInfo() {

  return "HttpSessionServlet Information";
 }
}

To invoke this servlet, you need to create an HTML file that will make a POST request containing a list of selected movies. The HTML file that contains this form is in Listing 5.5.

Listing 5.5 HtmlSessionServlet.html

<HTML>
<HEAD>
<TITLE>
Movie List
</TITLE>
</HEAD>

<BODY>
<H2>Select From Available Movies</h2>

<FORM ACTION=http://localhost/djs/servlet/HttpSessionServlet method=POST>

 <SELECT NAME="Movies" SIZE="5" MULTIPLE>
  <OPTION SELECTED>Air Force One</OPTION>
  <OPTION>Happy Gilmore</OPTION>
  <OPTION>So I Married an Axe Murderer</OPTION>
  <OPTION>Austin Powers</OPTION>
  <OPTION>Pure Luck</OPTION>
 </SELECT><BR>
 <INPUT TYPE="Submit" NAME="add" VALUE="Add Movies">

</FORM>

</BODY>
</HTML>

To see how this example works, load this HTML page in a browser. You should see a screen similar to Figure 5.2.

Figure 5.2 The Movie Selection List screen.

When this page is loaded, select a couple of the movies in the list and click the Add Movies button. You should now see a screen containing the list of movies you selected. Figure 5.3 displays an example of this output.

Figure 5.3 The Contents of Shopping Cart screen.

To understand how this first part works, you need to examine the doPost() method. This is the method that services the POST request sent by your HTML document.

The first thing the doPost() method does is get the list of submitted movies from the request. It then tries to get a reference to the HttpSession object stored in the HttpServletRequest. This is done by calling the HttpServletRequest.getSession() method. The code snippet that performs this is listed in the following:

// Get a handle to the HttpSession Object
// if there is no session create one
HttpSession session = request.getSession(true);

The getSession() method takes one parameter. This parameter is a Boolean value that, if true, tells the method to create an HttpSession if one doesn't exist.

When you have a reference to the HttpSession object, you can add your movie list to it. You do this by calling the HttpSession.setAttribute() method, passing it the name "Movies" and the object to be bound to it: movies. The movie list is now stored in the client's session. The last thing you do in the doPost() method is redisplay the list of selected movies and ask the user to click Proceed to Checkout.

NOTE

Sessions do expire. Therefore, you will need to consult your server's documentation to determine the length of time a session is valid.

Now you are going to look at the really cool part. Click the Proceed to Checkout button You shou.ld see a screen similar to Figure 5.4, which tells you "Thank you for purchasing:" and displays the movies you selected.

Figure 5.4 The thank you screen.

The request performed by this form simply calls the same servlet using the GET method. If you look at the URL your browser now points to, you will notice there is no movie data encoded in the URL string.

Look at the doGet() method to see exactly how this is done. The first thing you do is get a reference to the HttpSession object, which is done exactly as before with the getSession() method. When you have a reference to the session, you can get the list of movies stored in the session. You do this by calling the HttpSession.getAttribute() method, passing it the name bound to the movies object. The following code snippet shows how this is done:

// Get the movies list object bound to the
// name "Movies"
if ( session != null ) {

movies = (String[ ])session.getAttribute("Movies");
}

NOTE

Make sure that you downcast your stored object back to its original type. While in the HttpSession, it is stored as an object.

When you have the list of movies, thank the customer for the purchase and redisplay the list of ordered movies. That is all there is to it. As you have seen, the Servlet API provides you with a very elegant and simple-to-use method of maintaining persistent sessions.

  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.