background image

Session Tracking

<< Associating Objects with a Session | Finalizing a Servlet >>
<< Associating Objects with a Session | Finalizing a Servlet >>

Session Tracking

You can also set the timeout period in the deployment descriptor using NetBeans IDE:
1. Open the web.xml file in the web.xml editor.
2. Click General at the top of the editor.
3. Enter an integer value in the Session Timeout field. The integer value represents the number
of minutes of inactivity that must pass before the session times out.
To ensure that an active session is not timed out, you should periodically access the session by
using service methods because this resets the session's time-to-live counter.
When a particular client interaction is finished, you use the session's invalidate method to
invalidate a session on the server side and remove any session data. The bookstore application's
ReceiptServlet
is the last servlet to access a client's session, so it has the responsibility to
invalidate the session:
public class ReceiptServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Get the user
's session and shopping cart
HttpSession session = request.getSession();
// Payment received -- invalidate the session
session.invalidate();
...
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") +
Maintaining Client State
Chapter 4 · Java Servlet Technology
127