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: ...
Get Java Extreme Programming Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.