Recipe 7.1 Handling a POST HTTP Request in a Servlet


Problem

You want to process data that is part of a POST request.

Solution

Use the ServletRequest.getParameter(String name ) , getParameterMap( ) , getParameterNames( ) , or getParameterValues(String name) methods in the servlet's doPost method.

Discussion

The service method of a servlet calls the servlet's doPost method when a client sends a POST HTTP request. The servlet developer then has four different methods she can call to gain access to the posted data, which makes it pretty easy to process these requests . Just in case a client application uses a GET method to send the servlet its data as a query string, the servlet should also call:

 doPost(request,response); 

in the servlet's doGet( ) method. Example 7-2 demonstrates handling POST data with the oft-used getParameter(String name) method, as well as with the getParameterMap( ) method, which returns a java.util.Map . The map contains parameter keys and values. The getParameterNames( ) method returns a java.util.Enumeration of the parameter names . You can iterate through this Enumeration and pass the values to getParameter(String name) . Another ServletRequest method, getParameterValues(String name) , returns a String array of all the posted values for that parameter name (if there is only one value, the returned array contains one String ). Figure 7-1 shows the browser display of the PostHandler servlet after a user has submitted the form in Example 7-1.

Figure 7-1. Servlet displays name/value pairs from posted form input
figs/jsjc_0701.gif
Example 7-2. Using the ServletRequest.getParameter and getParameterMap methods to handle posted data
 import javax.servlet.*; import javax.servlet.http.*;  import java.util.Map; import java.util.Iterator; import java.util.Map.Entry;  public class PostHandler extends HttpServlet {     public void doPost(HttpServletRequest request, HttpServletResponse response) throws  ServletException, java.io.IOException {          /* Use the ServletRequest.getParameter(String name), getParameterMap( ),  getParameterNames( ), or getParameterValues( ) methods in the servlet's doPost method*/  String name = request.getParameter("username");     String depart = request.getParameter("department");     String email = request.getParameter("email");  response.setContentType("text/html");     java.io.PrintWriter out = response.getWriter( );            out.println("<html>");     out.println("<head>");     out.println("<title>Welcome</title>");       out.println("</head>");     out.println("<body>");     out.println("<h1>Your Identity</h1>");  out.println(         "Your name is: " + ( (name == null   name.equals("")) ?              "Unknown" : name));  out.println("<br><br>");  out.println(        "Your department is: " + ( (depart == null   depart.equals("")) ?            "Unknown" : depart));  out.println("<br><br>");  out.println(         "Your email address is: " + ( (email == null                email.equals("")) ? "Unknown" : email));  out.println("<h2>Using ServletRequest.getParameterMap</h2>");  Map param_map = request.getParameterMap( );  if (param_map == null)         throw new ServletException(             "getParameterMap returned null in: " +                 getClass( ).getName( ));  //iterate through the java.util.Map and display posted parameter     //values     //the keys of the Map.Entry objects are type String; the values are     //type String[],     //or String array     Iterator iterator = param_map.entrySet( ).iterator( );         while(iterator.hasNext( )){             Map.Entry me = (Map.Entry)iterator.next( );             out.println(me.getKey( ) + ": ");             String[] arr = (String[]) me.getValue( );             for(int i=0;i<arr.length;i++){                 out.println(arr[i]);                 //print commas after multiple values,                  //except for the last one                 if (i > 0 && i != arr.length-1)                 out.println(", ");             }//end for                 out.println("<br><br>");         }//end while  out.println("</body>");         out.println("</html>");            }       public void doGet(HttpServletRequest request, HttpServletResponse response)     throws ServletException, java.io.IOException {  doPost(request,response);  } } 

Getting the value of a parameter is as simple as using request.getParameter( parametername ) . Then you can test for the failure to return a valid value with code from Example 7-2:

 out.println("Your name is: " +     ( (name == null   name.equals("")) ? "Unknown" : name)); 

If the name variable is an empty String or null , then the servlet prints "Unknown"; otherwise , it prints the name value. There are several design patterns you can use for validating form input, including client-side JavaScript and special validation JavaBeans.

Handling the java.util.Map type is more involved and entails more code. The servlet gets the parameter map by calling the ServletRequest method:

 Map param_map = request.getParameterMap( ) 

Then the code gets a java.util.Iterator from the java.util.Set returned from Map.entrySet( ) . The Set contains Map.Entry objects, which are key/value pairs representing the parameter name and value. The servlet uses the iterator to cycle through the parameter names and values:

 Iterator iterator = param_map.entrySet( ).iterator( ); while(iterator.hasNext( )){     Map.Entry me = (Map.Entry)iterator.next( );     out.println(me.getKey( ) + ": ");     // The returned value is a String array     String[] arr = (String[]) me.getValue( );     for(int i=0;i<arr.length;i++){         out.println(arr[i]);        //print commas after multiple values,         //except for the last one        if (i > 0 && i != arr.length-1)            out.println(", ");     }//end for     out.println("<br><br>"); }//end while 

If this looks too elaborate for processing posted data, then reserve getParameterMap( ) for applications that are designed to deal with them, such as a validator bean that takes a Map as a constructor or method parameter. In addition, Recipe 7.2 shows a JSP that uses JSTL to conveniently process a parameter map.

See Also

Recipe 7.2 on handling a POST request in a JSP; Recipe 7.5 on posting data from a servlet; Recipe 7.7 on using a servlet to add a parameter to a query string; the ServletRequest API docs at http://java.sun.com/j2ee/1.4/docs/api/index.html.



Java Servlet & JSP Cookbook
Java Servlet & JSP Cookbook
ISBN: 0596005725
EAN: 2147483647
Year: 2004
Pages: 326

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net