The Java EE 5 Tutorial

Session Tracking

A web container can use several methods to associate a session with a user, all of which involve passing an identifier between the client and the server. The identifier can be maintained on the client as a cookie, or the web component can include the identifier in every URL that is returned to the client.

If your application uses session objects, you must ensure that session tracking is enabled by having the application rewrite URLs whenever the client turns off cookies. You do this by calling the response’s encodeURL(URL) method on all URLs returned by a servlet. This method includes the session ID in the URL only if cookies are disabled; otherwise, it returns the URL unchanged.

The doGet method of ShowCartServlet encodes the three URLs at the bottom of the shopping cart display page as follows:

out.println("<p> &nbsp; <p><strong><a href=\"" +
    response.encodeURL(request.getContextPath() +
        "/bookcatalog") +
        "\">" + messages.getString("ContinueShopping") +
        "</a> &nbsp; &nbsp; &nbsp;" +
        "<a href=\"" +
    response.encodeURL(request.getContextPath() +
        "/bookcashier") +
        "\">" + messages.getString("Checkout") +
        "</a> &nbsp; &nbsp; &nbsp;" +
        "<a href=\"" +
     response.encodeURL(request.getContextPath() +
        "/bookshowcart?Clear=clear") +
        "\">" + messages.getString("ClearCart") +
        "</a></strong>");

If cookies are turned off, the session is encoded in the Check Out URL as follows:


http://localhost:8080/bookstore1/cashier;jsessionid=c0o7fszeb1

If cookies are turned on, the URL is simply


http://localhost:8080/bookstore1/cashier