O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required