Sunday 11 September 2011

Handling HTTP POST Requests


Handling HTTP POST Requests
The following servlet 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.html and a servlet is defined in ColorPostServlet.java.

ColorPost.html

<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>

ColorPostServlet.java
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();
}
}

No comments:

Post a Comment