![]() |
![]() |
![]() |
![]() |
![]() |
|
What you have learned about cookies is put to use in the following revision
of the servlet, ProcessCriticFormServlet, defined previously in
Segment 1049. Note that, because cookie values are always
strings, you must convert them to int
values.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ProcessCriticFormServlet extends HttpServlet {
public void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Process arguments
String title = request.getParameter("title");
String script = request.getParameter("script");
String acting = request.getParameter("acting");
String direction = request.getParameter("direction");
// Cookie processing
int voteCount = 0;
Cookie [] cookies = request.getCookies();
System.out.println("There are " + cookies.length + " cookies");
// Look for existing cookie
for (int i = 0; i < cookies.length; ++i) {
if("votes".equals(cookies[i].getName())) {
voteCount = Integer.parseInt(cookies[i].getValue());
}
}
// Write new cookie
++voteCount;
Cookie cookie = new Cookie("votes", String.valueOf(voteCount));
response.addCookie(cookie);
// Writing preparation
response.setContentType("text/html");
PrintWriter webWriter = response.getWriter();
// Writing HTML page goes here
// New line informing users of the vote count
webWriter.println("You have cast "
+ voteCount
+ (voteCount == 1 ? " vote" : " votes")
+ " so far<p>");
// Rest of writing HTML page goes here
// File output goes here
}}