O'Reilly logo

Head First Servlets and JSP, 2nd Edition by Bert Bates, Bryan Basham, Kathy Sierra

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

Sending and using TWO parameters

HTML form

image with no caption

HTTP POST request

image with no caption

Servlet class

public void doPost(HttpServletRequest request, HttpServletResponse response)
                                             throws IOException, ServletException {
   String colorParam = request.getParameter("color");
   String bodyParam = request.getParameter("body");
     // more code here
}

Note

Now the String variable colorParam has a value of “dark” and bodyParam has a value of “heavy”.

Watch it!

You can have multiple values for a single parameter! That means you’ll need getParameterValues() that returns an array, instead of getParameter() that returns a String.

Some form input types, like a set of checkboxes, can have more than one value. That means a single parameter (“sizes”, for example) will have multiple values, depending on how many boxes the user checked off. A form where a user can select multiple beer sizes (to say that he’s interested in ALL of those sizes) might look like this:

<form method=POST
 action="SelectBeer.do">
 Select beer characteristics<p>
 Can Sizes: <p>
 <input type=checkbox name=sizes value="12oz"> 12 oz.<br>
 <input type=checkbox name=sizes value="16oz"> 16 oz.<br>
 <input type=checkbox name=sizes value="22oz"> 22 oz.<br>
 <br><br>

 <center>
   <input type="SUBMIT">
 </center>
</form>

In your code, you’ll use the getParameterValues() method that returns an array:

String one = request.getParameterValues("sizes")[0];

String [] sizes = request.getParameterValues("sizes");

If you want to see everything in the array, just for fun or testing, you can use:

String [] sizes = request.getParameterValues("sizes");
for(int x=0; x < sizes.length ; x++) {
   out.println("<br>sizes: " + sizes[x]);
}

(assume that “out” is a PrintWriter you got from the response)

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