Java Reference
In-Depth Information
Retrieving Form Data in a Servlet
We will now look at how servlets retrieve information from the client. Servlets most commonly
receive data from both POST and GET requests. The methods used to retrieve this data are the
same in either case.
The three methods used to retrieve request parameters are the ServletRequest 's
getParameterNames() , getParameter() , and getParameterValues() . Their signatures are as
follows:
public Enumeration ServletRequest.getParameterNames();
public String ServletRequest.getParameter(String name);
public String[] ServletRequest.getParameterValues(String name);
getParameterNames() returns the parameter names for the request as an enumeration of
strings, or an empty enumeration if there are no parameters. It is used as a supporting method
to getParameter() . When you have the enumerated list of parameter names, you can iterate
over them calling getParameter() with each name in the list.
The getParameter() method returns a string containing the single value of the specified para-
meter, or null if the parameter is not contained in the request. This method should be used only
if you are sure the request contains only one value for the parameter. If the parameter has mul-
tiple values you should use getParameterValues() .
getParameterValues() returns the values of the specified parameter as an array of strings, or
null if the named parameter does not exist in the request.
Servicing the GET and POST Requests
Let's take a look at a servlet that services a POST request. The servlet in Listing 4.1 retrieves
the parameters sent to it and returns the parameters and their values back to the client.
L ISTING 4.1
FormServlet.java Displays All Parameter/Value Pairs in Request
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class FormServlet extends HttpServlet {
public void init(ServletConfig config)
throws ServletException {
// Always pass the ServletConfig object to the super class
Search WWH ::




Custom Search