Environment Used
- JDK 6 (Java SE 6) (To install JDK – Windows , Ubuntu)
- Eclipse Indigo IDE for Java EE Developers (3.7.1) (To install Eclipse, refer this page)
- Apache Tomcat 6.x (To install Tomcat refer this page)
- Java EE 5 API (Servlet 2.5)
- [Optional] For monitoring and analyzing HTTP headers between the browser and web servers, you can use one of these add-ons of Firefox
- Live HTTP Headers
- HttpFox
Setting up development environment
If you are new to developing Servlet with Tomcat and Eclipse, you can read this page before proceeding with this example.
Project Description
- This example explains how to read all parameters in HTML form using Servlet.
- In this application we create a simple Pizza order form which allows user to order Pizza by filling the HTML form. The form is submitted to the Servlet which reads all the parameters and displays the details filled by the user.
- We use Eclipse IDE for Java EE Developers and Apache Tomcat to run the Servlet.
Reading all parameters in HTML form
The method getParameterMap() from javax.servlet.ServletRequest is used to get all form data.
Method signature:
Map getParameterMap()
- Returns an immutable java.util.Map containing parameter names as keys and parameter values as map values.
- The keys in the parameter map are of type String. The values in the parameter map are of type String array.
- For Servlets, parameters are contained in the query string (GET request) or request body (POST request).
- If the request has no parameters, the method returns an empty Map.
HTML Form
<html> <head> <title>Retrieving All Parameters</title> </head> <body> <h4>Order your Pizza Here</h4> <form action="allparams.do" method="post"> <b>Name</b> <input type="text" name="name"><br><br> <b>Select the Crust:</b> <select name = "crust"> <option value="pan">Pan</option> <option value="thin">Thin Crust</option> <option value="deep">Deep Crust</option> <option value="cheese">Cheese Burst</option> </select> <br><br> <b>Toppings: </b><br> <input type="checkbox" name="toppings" value="peas">Peas<br> <input type="checkbox" name="toppings" value="paneer">Paneer<br> <input type="checkbox" name="toppings" value="redpeppers">Red Peppers<br> <input type="checkbox" name="toppings" value="pineapple">Pineapple<br> <input type="checkbox" name="toppings" value="onion">Onion<br> <input type="checkbox" name="toppings" value="tomato">Tomato<br><br> <b>Select 1 FREE Appetizer</b> <input type="radio" name="appetizer" value="Garlic Bread">Garlic Bread <input type="radio" name="appetizer" value="Cheese Garlic Bread">Cheese Garlic Bread <input type="radio" name="appetizer" value="Veg Soup">Veg Soup <input type="radio" name="appetizer" value="Veg Sandwich">Veg Sandwich<br><br> <b>Address</b><br> <textarea name="address" rows=3 cols=40></textarea><br><br> <b>Credit Card:</b><br> <input type="radio" name="cardType" value="Visa">Visa <input type="radio" name="cardType" value="MasterCard">MasterCard <input type="radio" name="cardType" value="Amex">American Express <br><br> <b>Credit Card Number:</b> <input type="password" name="cardNum"> <b>Repeat Credit Card Number: </b><input type="password" name="cardNum"><br><br> <input type="submit" name="submit" value="Order Pizza"> </form> </body> </html>
Servlet Code
package com.theopentutorials.servlets; import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class RetrievingAllParams extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Map<String, String[]> map = request.getParameterMap(); PrintWriter out = response.getWriter(); response.setContentType("text/html"); out.print("<html><body>"); out.print("<h1> Your Order...</h1>"); out.println("<table border=\"1\" cellpadding = \"5\"" + " cellspacing = \"5\">"); out.println("<tr> <th>Parameter Name</th>" + "<th>Parameter Value</th></tr>"); Set set = map.entrySet(); Iterator it = set.iterator(); while (it.hasNext()) { Map.Entry<String, String[]> entry = (Entry<String, String[]>) it.next(); String paramName = entry.getKey(); out.print("<tr><td>" + paramName + "</td><td>"); String[] paramValues = entry.getValue(); if (paramValues.length == 1) { String paramValue = paramValues[0]; if (paramValue.length() == 0) out.println("<b>No Value</b>"); else out.println(paramValue); } else { out.println("<ul>"); for (int i = 0; i < paramValues.length; i++) { out.println("<li>" + paramValues[i] + "</li>"); } out.println("</ul>"); } out.print("</td></tr>"); } out.println("</table></body></html>"); } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation= "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <servlet> <servlet-name>AllParamsMap</servlet-name> <servlet-class>com.theopentutorials.servlets.RetrievingAllParams</servlet-class> </servlet> <servlet-mapping> <servlet-name>AllParamsMap</servlet-name> <url-pattern>/allparams.do</url-pattern> </servlet-mapping> </web-app>
Project Folder Structure
The complete directory structure of this project is shown below.
Output
Program Control Flow
- Web client (browser) requests the server/container for the HTML file (allparams.html) through request URL.
- Container responses with the actual content of HTML file along with HTTP response headers.
- When the user submits the form, web client sends request to the Servlet along with all form data in the body of HTTP header since it is a POST request.
- Servlet uses getParameterMap() to get all form parameters and responds with the actual HTML content.
The content of HTTP request and response headers can be monitored using browser add-ons such as Live HTTP Headers, HttpFox, etc
Sample HTTP request and response headers using these add-ons is shown below.
HTTP Request
http://localhost:8080/ReqAndResChapter4/allparams.html GET /ReqAndResChapter4/allparams.html HTTP/1.1 Host: localhost:8080 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-gb,en;q=0.5 Accept-Encoding: gzip,deflate Connection: keep-alive ….. ….. |
HTTP Response
HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Accept-Ranges: bytes Content-Type: text/html Content-Length: 1957 Content: HTML Form (allparams.html) … |
HTTP Request
Form parameter in Request body, since it is a POST request.
HTTP Response
To develop and run this example with Tomcat and Eclipse, refer this page.