15

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);
    }
}
Mike
  • 14,010
  • 29
  • 101
  • 161
NNikN
  • 3,720
  • 6
  • 44
  • 86

1 Answers1

22

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

Mike
  • 14,010
  • 29
  • 101
  • 161
kamoor
  • 2,909
  • 2
  • 19
  • 34
  • thanks, could you please explain with some post data example, suitable for approach 1 and 2? – NNikN Jan 01 '15 at 15:56
  • When I try the following url, I get 1 map member (key: r), and its an array with two elements [123123,98734]. https://localhost/app/faces/main.xhtml?r=123123&r=98734 – Harun Dec 07 '15 at 22:35
  • Often "lost"..is yes, you can (just fine) have ?myQueryStringNameOne=aaa&myQueryStringNameOne=bbb&myQueryStringNameOne=ccc – granadaCoder Dec 17 '20 at 00:42