ServletRequest.getParameterMap() returns Map<String, String[]> and ServletRequest.getParameter() returns String?

JavaServlets

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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"));

Solution 2 - Java

http://foo.com/bar?biff=banana&biff=pear&biff=grape

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

Solution 3 - Java

The real function to get all parameter values is

   request.getParameterValues();

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

Solution 4 - Java

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

Solution 5 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBillManView Question on Stackoverflow
Solution 1 - JavaBalusCView Answer on Stackoverflow
Solution 2 - JavaJonathan FeinbergView Answer on Stackoverflow
Solution 3 - JavaZZ CoderView Answer on Stackoverflow
Solution 4 - JavaBozhoView Answer on Stackoverflow
Solution 5 - JavaSteve B.View Answer on Stackoverflow