HTTPServletRequest getParameterMap() vs getParameterNames

天大地大妈咪最大 提交于 2019-12-05 14:40:44

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/27732133/httpservletrequest-getparametermap-vs-getparameternames

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!