Session Tracking (2024)

Session tracking is a mechanism that servlets use to maintain state about aseries of requests from the same user (that is, requests originating from thesame browser) across some period of time.

Sessions are shared among the servlets accessed by a client. This isconvenient for applications made up of multiple servlets. For example,Duke's Bookstore uses session tracking to keep track of the books beingordered by a user. All the servlets in the example have access to the user'ssession.

To use session tracking,

  • Obtain a session (anHttpSessionSession Tracking (1) object) for a user.
  • Store or get data from the HttpSession object.
  • Invalidate the session (optional).

Obtaining a Session

The getSession method of theHttpServletRequest object returns a user's session. When youcall the method with its create argument as true,the implementation creates a session if necessary.

To properly maintain the session, you must call getSessionbefore any output is written to the response. (If you respond using aWriter, then you must call getSession beforeaccessing the Writer, not just before sending any response data.)

The Duke's Bookstore example usessession tracking to keep track of the books in the user's shopping cart.Here is an example of the CatalogServlet obtaining a sessionfor a user:

 public class CatalogServlet extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the user's session and shopping cart HttpSession session = request.getSession(true); ... out = response.getWriter(); ... } }

Storing and Getting Data from a Session

The HttpSession interface provides methods that store andreturn:
&nbsp:

  • Standard session properties, such as a session identifier
  • Application data, which is stored as a name-value pair, where the nameis a String and the value is an object in the Java programminglanguage. (This is like java.util.Dictionary.) Becausemultiple servlets have access to a user's session, you should adopt anaming convention for organizing the names associated with applicationdata. This avoids servlets accidentally overwriting each other's values inthe session. One such convention is servletname.namewhere servletname is the full name of the servlet,including its packages. For example,com.acme.WidgetServlet.state is a cookie with theservletname com.acme.WidgetServlet and the namestate.

The Duke's Bookstore example uses session tracking to keep trackof the books in the user's shopping cart. Here is an example of theCatalogServlet getting a user's session identifier, andgetting and setting the application data associated with the user'ssession:

 public class CatalogServlet extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the user's session and shopping cart HttpSession session = request.getSession(true); ShoppingCart cart = (ShoppingCart)session.getValue(session.getId()); // If the user has no cart, create a new one if (cart == null) { cart = new ShoppingCart(); session.putValue(session.getId(), cart); } ... } }

Because an object can be associated with a session, the Duke'sBookstore example keeps track of the books that a user has ordered withinan object. The object is type ShoppingCart and each book that auser orders is stored in the shopping cart as a ShoppingCartItemobject. For example, the following comes from further down in thedoGet method of the CatalogServlet:

 public void doGet (HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {HttpSession session = request.getSession(true);ShoppingCart cart = (ShoppingCart)session.getValue(session.getId()); ... // Check for pending adds to the shopping cart String bookId = request.getParameter("Buy"); //If the user wants to add a book, add it and print the result String bookToAdd = request.getParameter("Buy"); if (bookToAdd != null) { BookDetails book = database.getBookDetails(bookToAdd); cart.add(bookToAdd, book); out.println("<p><h3>" + ...); } }

Finally, note that a session can be designated as new. A newsession causes the isNew method of the HttpSessionclass to return true, indicating that, for example, the clientdoes not yet know about the session. A new session has no associated data.

You must deal with situations involving new sessions. In the Duke'sBookstore example above, if the user has no shopping cart (the only dataassociated with a session), the servlet creates a new one. Alternatively,if you need information from the user to start a session (such as auser-name), you might want to redirect the user to an "starting page" whereyou collect the necessary information.

Invalidating the Session

A user's session can be invalidated manually or, depending on where theservlet is running, automatically. (For example, the Java Web Serverautomatically invalidates a session when there have been no page requests insome period of time, 30 minutes by default.) To invalidate a session means toremove the HttpSession object and its values from the system.

To manually invalidate a session, use the session'sinvalidate method. Some applications have a natural point atwhich to invalidate the session. The Duke's Bookstore exampleinvalidates a user's session after the user has bought the books. Thishappens in the ReceiptServlet:

 public class ReceiptServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... scart = (ShoppingCart)session.getValue(session.getId()); ... // Clear out shopping cart by invalidating the session session.invalidate(); // set content type header before accessing the Writer response.setContentType("text/html"); out = response.getWriter(); ... } }

Handling All Browsers

By default, session tracking uses cookies to associate a sessionidentifier with a user. To also support users that access a servlet with abrowser that does not support cookies, or that is set up to reject cookies,you must use URL rewriting instead. (While some web servers support URLrewriting, the servletrunner utility does not. For sessiontracking to work when a servlet is running withinservletrunner, the user agent must support cookies.)

When you use URL rewriting you call methods that, when necessary,include the session ID in a link. You must call these methods for everylink in the servlet response.

The method that associates a session ID with a URL isHttpServletResponse.encodeUrl. If you redirect the user toanother page, the method to associate the session ID with the redirectedURL is called HttpServletResponse.encodeRedirectUrl.

The encodeUrl and encodeRedirectUrl methodsdecide whether the URL needs to be rewritten, and return the URL eitherchanged or unchanged. (The rules for URLs and redirected URLS differ, but ingeneral if the server detects that the browser supports cookies, then the URLis not rewritten.)

The Duke's Bookstore example uses URL rewriting for all of thelinks that it returns to its users. For example, theCatalogServlet returns the catalog with two links for eachbook. One link offers details about the book and the other allows you toadd the book to your shopping cart. Both URLs are rewritten:

 public class CatalogServlet extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the user's session and shopping cart, the Writer, etc. ... // then write the data of the response out.println("<html>" + ...); ... // Get the catalog and send it, nicely formatted BookDetails[] books = database.getBooksSortedByTitle(); ... for(int i=0; i < numBooks; i++) { ... //Print out info on each book in its own two rows out.println("<tr>" + ... "<a href=\"" + response.encodeUrl("/servlet/bookdetails?bookId=" + bookId) + "\"> <strong>" + books[i].getTitle() + " </strong></a></td>" + ... "<a href=\"" + response.encodeUrl("/servlet/catalog?Buy=" + bookId) + "\"> Add to Cart </a></td></tr>" + } } }

If the user clicks on a link with a rewritten URL, the servletrecognizes and extracts the session ID. Then the getSessionmethod uses the session ID to get the user's HttpSessionobject.

On the other hand, if the user's browser does not support cookies andthe user clicks on an un-rewritten URL, the user's session is lost. Theservlet contacted through that link creates a new session, but the newsession does not have the data associated with the previous session. Oncea servlet loses the session data, the data is lost for all servlets thatshare the session. You should consistently use URL rewriting if yourservlet is to support clients that do not support or accept cookies.

Session Tracking (2024)
Top Articles
Latest Posts
Article information

Author: Edwin Metz

Last Updated:

Views: 6178

Rating: 4.8 / 5 (58 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Edwin Metz

Birthday: 1997-04-16

Address: 51593 Leanne Light, Kuphalmouth, DE 50012-5183

Phone: +639107620957

Job: Corporate Banking Technician

Hobby: Reading, scrapbook, role-playing games, Fishing, Fishing, Scuba diving, Beekeeping

Introduction: My name is Edwin Metz, I am a fair, energetic, helpful, brave, outstanding, nice, helpful person who loves writing and wants to share my knowledge and understanding with you.