51

Can someone explain to me why ServletRequest.getParameterMap() returns type

Map<String, String[]> 

ServletRequest.getParameter() just returns type String

I'm don't understand why the map would ever map to more then one value. TIA.

BillMan
  • 8,837
  • 9
  • 31
  • 52

5 Answers5

56

It returns all parameter values for controls with the same name.

For example:

<input type="checkbox" name="cars" value="audi" /> Audi
<input type="checkbox" name="cars" value="ford" /> Ford
<input type="checkbox" name="cars" value="opel" /> Opel

or

<select name="cars" multiple>
    <option value="audi">Audi</option>
    <option value="ford">Ford</option>
    <option value="opel">Opel</option>
</select>

Any checked/selected values will come in as:

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

It's also useful for multiple selections in tables:

<table>
    <tr>
        <th>Delete?</th>
        <th>Foo</th>
    </tr>
    <c:forEach items="${list}" var="item">
        <tr>
            <td><input type="checkbox" name="delete" value="${item.id}"></td>
            <td>${item.foo}</td>
        </tr>
    </c:forEach>
</table>

in combination with

itemDAO.delete(request.getParameterValues("delete"));
BalusC
  • 1,040,783
  • 362
  • 3,548
  • 3,513
  • 5
    Thanks for the feedback. It make perfect sense now. Sometimes it's easy to miss the obvious stuff. I guess that's what this web site if for :). – BillMan Dec 18 '09 at 15:19
21
http://foo.com/bar?biff=banana&biff=pear&biff=grape

"biff" now maps to {"banana","pear","grape"}

Jonathan Feinberg
  • 43,499
  • 6
  • 78
  • 102
10

The real function to get all parameter values is

   request.getParameterValues();

getParameter() is just a shortcut to get first one.

ZZ Coder
  • 72,880
  • 29
  • 134
  • 165
3

In the case with multi-value controls (checkbox, multi-select, etc), the request.getParameterValues(..) is used to fetch the values.

Bozho
  • 572,413
  • 138
  • 1,043
  • 1,132
2

If you have a multi-value control like a multi-selectable list or a set of buttons mapped to the same name multiple selections will map to an array.

Steve B.
  • 52,726
  • 11
  • 92
  • 128
  • I am not sure if I see the value in case of buttons. In decent browsers it will only return the value of the **pressed** button, not the value of **all** buttons. – BalusC Dec 18 '09 at 15:29