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);
}
}
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.
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 .
java - Servlet request. getParameter() always return null value - Stack Overflow.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With