Listing 8.5 redoes the RepeatVisitor servlet of Listing 8.1. The new version ( RepeatVisitor2 ) has the same functionality as the old version: it says "Welcome Aboard" to first-time visitors and "Welcome Back" to repeat visitors . However, it uses the cookie utilities of Section 8.8 to simplify the code in two ways:
Figures 8-8 and 8-9 show the results. Listing 8.5 RepeatVisitor2.javapackage coreservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; /** A variation of the RepeatVisitor servlet that uses * CookieUtilities.getCookieValue and LongLivedCookie * to simplify the code. */ public class RepeatVisitor2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean newbie = true; String value = CookieUtilities.getCookieValue(request, "repeatVisitor2", "no"); if (value.equals("yes")) { newbie = false; } String title; if (newbie) { LongLivedCookie returnVisitorCookie = new LongLivedCookie("repeatVisitor2", "yes"); response.addCookie(returnVisitorCookie); title = "Welcome Aboard"; } else { title = "Welcome Back"; } response.setContentType("text/html"); PrintWriter out = response.getWriter(); String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n"; out.println(docType + "<HTML>\n" + "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" + "</BODY></HTML>"); } } Figure 8-8. First visit by a client to the RepeatVisitor2 servlet.
Figure 8-9. Subsequent visit by a client to the RepeatVisitor2 servlet.
|