Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    }
}
like image 626
NNikN Avatar asked Jan 01 '15 15:01

NNikN


People also ask

What is getParameterMap?

getParameter(String name) Returns the value of a request parameter as a String , or null if the parameter does not exist. Map. getParameterMap() Returns a java.

What is the return type of getParameterNames () method?

getParameterNames. Returns an Enumeration of String objects containing the names of the parameters contained in this request. If the request has no parameters, the method returns an empty Enumeration .

Do servlets getParameterNames always return?

java - Servlet request. getParameter() always return null value - Stack Overflow.

Which method of the HttpServletRequest object is used if there is a chance of retrieving multiple?

If there's any chance a parameter could have more than one value, you should use the getParameterValues( ) method instead. This method returns all the values of the named parameter as an array of String objects or null if the parameter was not specified.


1 Answers

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

like image 66
kamoor Avatar answered Oct 07 '22 20:10

kamoor