如何以 PHP 和 Rails 的风格获取 Java 数组的请求参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/860041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 14:06:26  来源:igfitidea点击:

How to get request parameter to an array in Java, in the style of PHP and Rails?

javaparametersrequest

提问by adnan.

The situation is as follows:

情况如下:

page.jsp?var[0]=foo&var[1]=bar

How can this be retrieved in an array in Java?

如何在 Java 的数组中检索它?

The following:

下列:

page.jsp?var=foo&var=bar

I know can be retrieved using request.getParameterValues("var")

我知道可以使用 request.getParameterValues("var") 检索

Any solutions for the above though?

以上问题有什么解决办法吗?

采纳答案by Pierre

Map<Integer,String> index2value=new HashMap<Integer,String>();

for (Enumeration e = request.getParameterNames(); e.hasMoreElements() ;)
 {
 String param= e.nextElement().toString();
 if(!param.matches("var\[[0-9]+\]")) continue;
 int index= (here extract the numerical value....)
 index2value.put(index,request.getParameter(param));
 }

Hope this helps.

希望这可以帮助。

回答by sal

HashMap m = request.getParameterMap();
Set k = m.keySet();
Set v = m.entrySet();
Object o[] = m.entrySet().toArray();

That will get you a Map call m with K,V pairs and both a set of keys and set of values. You can iterate those sets almost like an array. You can also use toArray to turn it into an array.

这将为您提供带有 K、V 对以及一组键和一组值的 Map 调用 m。您几乎可以像数组一样迭代这些集合。您还可以使用 toArray 将其转换为数组。