img
.
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
OTE
is sent to the web server. In this example, the URL sent from the browser to the server is
http://localhost:8080/servlets-examples/servlet/ColorPostServlet.
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:
File
Description
AddCookie.htm
Allows a user to specify a value for the cookie named MyCookie.
AddCookieSer vlet.java
Processes the submission of AddCookie.htm.
GetCookiesSer vlet.java
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.
<html>
<body>
<center>
<form name="Form1"
method="post"
action="http://localhost:8080/servlets-examples/servlet/AddCookieServlet">
<B>Enter a value for MyCookie:</B>
<input type=textbox name="data" size=25 value="">
<input type=submit value="Submit">
</form>
</body>
</html>
The source code for AddCookieServlet.java 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 java.io.*;
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
Home