Handling HTTP POST Requests
Here we will develop a servlet that handles an HTTP POST request. The servlet is invoked
when a form on a web page is submitted. The example contains two files. A web page is
defined in ColorPost.htm, and a servlet is defined in ColorPostServlet.java.
The HTML source code for ColorPost.htm is shown in the following listing. It is identical
to ColorGet.htm except that the method parameter for the form tag explicitly specifies that
the POST method should be used, and the action parameter for the form tag specifies a
different servlet.
<html>
<body>
<center>
<form name="Form1"
method="post"
action="http://localhost:8080/servlets-examples/servlet/ColorPostServlet">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
The source code for ColorPostServlet.java is shown in the following listing. The doPost( )
method is overridden to process any HTTP POST requests that are sent to this servlet. It uses
the getParameter( ) method of HttpServletRequest to obtain the selection that was made
by the user. A response is then formulated.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorPostServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is:  ");
pw.println(color);
pw.close();
}
}
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home