HTTPServletRequest getParameterMap()与getParameterNames [英] HTTPServletRequest getParameterMap() vs getParameterNames

查看:167
本文介绍了HTTPServletRequest getParameterMap()与getParameterNames的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HTTPServletRequest req,具有方法getParameterMap(),但是对于后数据而言,值返回String[]而不是String,作为

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.

name=Marry&lastName=John&Age=20.

我在发布数据中看到它不是数组,但是getParameterMap()为每个键(名称,姓氏或年龄)返回数组.有没有更好地理解这一点的指针?

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?

方法2中提供了该代码.方法1可以很好地工作.

The code is available in Approach 2. Approach 1 works completely fine.

方法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 + ">");
}

方法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(java.lang.String name)方法.

If you are expecting pre determined parameters then you can use getParameter(java.lang.String name) method.

否则,可以使用上面给出的方法,但有一些区别,在HTTP请求中,某人可以发送一个或多个名称为相同的参数.

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.

例如:

name=John, name=Joe, name=Mia

方法1仅在您希望客户端仅发送一个名称的参数值时使用,其余的将被忽略.在此示例中,您只能阅读"John"

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"

如果期望多个具有相同名称的值,则可以使用方法2.如代码中所示,值将被填充为数组.因此,您将能够读取所有值,在此示例中为"John","Joe","Mia"

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

文档

这篇关于HTTPServletRequest getParameterMap()与getParameterNames的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆