Java Reference
In-Depth Information
￿ void setComment(String <value>)
(A comment is optionally used to describe the cookie.)
￿ String getComment()
￿ String getName()
￿ String getValue()
￿ void setValue(String <value>)
￿ int getMaxAge()
Example
This will be a modifi cation of the earlier 'Simple Adder' example. On the user's fi rst
visit to the site, he/she will be prompted to enter his/her name and a choice of both
foreground and background colours for the addition result page. These values will be
saved in cookies, which will be retrieved on subsequent visits to the site. If the user fails
to enter a name, there will be no personalised header. Failure to select a foreground
colour will result in a default value of black being set, whilst failure to select a back-
ground colour will result in a default value of white being set. The only differences in
the initial HTML fi le are in the lines giving the names of the two fi les involved:
<!-- CookieAdder.html -->
.............................................
.............................................
<FORM METHOD=POST ACTION=" CookieAdder">
.............................................
.............................................
Servlet CookieAdder will set up a new Session object, retrieve the user's cookies
and create session variables corresponding to those cookies. (A Session object is
preferable, since three servlets will be involved, all of which require access to the
data values. This saves each servlet from having to download the cookies sepa-
rately.) In addition to the contents of the cookies, the result of the addition will need
to be saved in a session variable. If the appropriate session variable indicates that
this is the user's fi rst visit to the site, method sendRedirect will be used to pass con-
trol to a preferences servlet. In order to avoid code duplication, control will also
need to be redirected to a result-displaying servlet from both the initial servlet and
the preferences servlet.
Here's the code for CookieAdder (the initial servlet):
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/CookieAdder")
public class CookieAdder extends HttpServlet
{
public void doPost(HttpServletRequest request,
HttpServletResponse response)
Search WWH ::




Custom Search