O'Reilly logo

Java Extreme Programming Cookbook by Brian M. Coyner, Eric M. Burke

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Testing Session Tracking Using HttpSession

Problem

You want to test that your servlet properly handles session tracking when using an HttpSession.

Solution

Write a ServletTestCase to test that your servlet properly handles adding and removing objects from an HttpSession.

Discussion

Servlet developers know that session tracking is critical for any web application that needs to maintain state between user requests. Since HTTP is a stateless protocol, it provides no way for a server to recognize consecutive requests from the same client. This causes problems with web applications that need to maintain information on behalf of the client. The solution to this problem is for the client to identify itself with each request. Luckily, there are many solutions to solving this problem. Probably the most flexible solution is the servlet session-tracking API. The session tracking API provides the constructs necessary to manage client information on the server. Every unique client of a web application is assigned a javax.servlet.http.HttpSession object on the server. The session object provides a little space on the server to hold information between requests. For each request, the server identifies the client and locates the appropriate HttpSession object.[39] The servlet may now add and remove items from a session depending on the user’s request.

This recipe focuses on the popular “shopping cart.” The shopping cart example is good because it is easy to understand. Our shopping cart is very simple: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required