Hidden Form Fields

One way to support anonymous session tracking is to use hidden form fields. As the name implies, these are fields added to an HTML form that are not displayed in the client’s browser. They are sent back to the server when the form that contains them is submitted. You include hidden form fields with HTML like this:

<FORM ACTION="/servlet/MovieFinder" METHOD="POST">
...
<INPUT TYPE=hidden NAME="zip" VALUE="94040">
<INPUT TYPE=hidden NAME="level" VALUE="expert">
...
</FORM>

In a sense, hidden form fields define constant variables for a form. To a servlet receiving a submitted form, there is no difference between a hidden field and a visible field.

With hidden form fields, we can rewrite our shopping cart servlets so that users can shop anonymously until check-out time. Example 7.1 demonstrates the technique with a servlet that displays the user’s shopping cart contents and lets the user choose to add more items or check out. An example screen for a bookworm is shown in Figure 7.1.

Example 7-1. Session tracking using hidden form fields

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ShoppingCartViewerHidden extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<HEAD><TITLE>Current Shopping Cart Items</TITLE></HEAD>"); out.println("<BODY>"); // Cart items are passed in as the item ...

Get Java Servlet Programming 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.