servletshttp-request-parameters

HTTPServletRequest getParameterMap() vs getParameterNames


HTTPServletRequest req, has a method getParameterMap() but, the values return a String[] instead of String, for post data as

name=Marry&lastName=John&Age=20.

I see in the post data it's not an array, but getParameterMap() returns array for every key(name or lastName or Age). Any pointers on understanding this in a better way?

The code is available in Approach 2. Approach 1 works completely fine.

Approach 1:

Enumeration<String> parameterNames = req.getParameterNames();

while (parameterNames.hasMoreElements()) {
    String key = (String) parameterNames.nextElement();
    String val = req.getParameter(key);
    System.out.println("A= <" + key + "> Value<" + val + ">");
}

Approach 2:

Map<String, Object> allMap = req.getParameterMap();

for (String key : allMap.keySet()) {
    String[] strArr = (String[]) allMap.get(key);
    for (String val : strArr) {
        System.out.println("Str Array= " + val);
    }
}

Solution

  • If you are expecting pre determined parameters then you can use getParameter(java.lang.String name) method.

    Otherwise, approaches given above can be used, but with some differences, in HTTP-request someone can send one or more parameters with the same name.

    For example:

    name=John, name=Joe, name=Mia
    

    Approach 1 can be used only if you expect client sends only one parameter value for a name, rest of them will be ignored. In this example you can only read "John"

    Approach 2 can be used if you expect more than one values with same name. Values will be populated as an array as you showed in the code. Hence you will be able to read all values, i.e "John","Joe","Mia" in this example

    Documentation