Compile the servlet and perform the same steps as described in the previous section
to test it.
NOTE  Parameters for an HTTP POST request are not included as part of the URL that
is sent to the web server. In this example, the URL sent from the browser to the server is
The parameter names and values are sent in the body of the HTTP request.
Using Cookies
Now, let's develop a servlet that illustrates how to use cookies. The servlet is invoked when
a form on a web page is submitted. The example contains three files as summarized here:
Allows a user to specify a value for the cookie named MyCookie.
Processes the submission of AddCookie.htm.
Displays cookie values.
The HTML source code for AddCookie.htm is shown in the following listing. This page
contains a text field in which a value can be entered. There is also a submit button on the
page. When this button is pressed, the value in the text field is sent to AddCookieServlet
via an HTTP POST request.
<form name="Form1"
<B>Enter a value for MyCookie:</B>
<input type=textbox name="data" size=25 value="">
<input type=submit value="Submit">
The source code for is shown in the following listing. It gets the
value of the parameter named "data". It then creates a Cookie object that has the name
"MyCookie" and contains the value of the "data" parameter. The cookie is then added to
the header of the HTTP response via the addCookie( ) method. A feedback message is then
written to the browser.
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCookieServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks