开发者

Why is the parameter value an Object hash code for `request.getParameterMap().get(name)`

Why is the parameter value an Object hash code:

input_name:[[Ljava.lang.String;@3f4d64]

I thought the code request.getParameterMap().get(name); would produce开发者_StackOverflow社区 the value of the request parameter:

    Enumeration params = request.getParameterNames();
    while(params.hasMoreElements())
    {
        String name = (String)params.nextElement(); 
        String value = request.getParameterMap().get(name);
        logger.log(name + ": " + value);
    }


Because it returns a String[], not a String. The javadoc of getParameterMap() also tells that:

Returns:

an immutable java.util.Map containing parameter names as keys and parameter values as map values. The keys in the parameter map are of type String. The values in the parameter map are of type String array.

So you need to treat it as an array. If you'd like to obtain a single (the first) parameter value, use request.getParameter() instead. Here's a rewrite:

for (String name : Collections.<String>list(request.getParameterNames())) {
    String value = request.getParameter(name); 
    logger.log(name + ": " + value);
}

Or if you really want to check all possible parameter values, then just iterate over the map's entryset:

Map<String, String[]> map = request.getParameterMap();
for (Entry<String, String[]> entry : map.entrySet()) {
    String name = entry.getKey();
    String[] values = entry.getValue();
    logger.log(name + ": " + Arrays.toString(values));
}


The parameter map is a map from parameter names to arrays of values. This is because you may have multiple values for the same parameter. Consider for instance the following request:

http://www.example.com/var=value1&var=value2

In this case you would get { "value1", "value2" } when getting the parameters for var.

If you want to print all values for a given parameter, you could use Arrays.toString on the array of values.

If you know that each variable has at most one value, you could use getParameter. From the docs:

You should only use this method when you are sure the parameter has only one value. If the parameter might have more than one value, use getParameterValues(java.lang.String).


The reason why HttpServletRequest have

Map<String, String[]> map = request.getParameterMap();

is because of Form Submit that have the same parameter names but different values. You can essentially have a URL form with 1 or more same parameter names with different values.

See BalusC response.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜