How to get request parameter to an array in Java, in the style of PHP and Rails?
-
21-08-2019 - |
Question
The situation is as follows:
page.jsp?var[0]=foo&var[1]=bar
How can this be retrieved in an array in Java?
The following:
page.jsp?var=foo&var=bar
I know can be retrieved using request.getParameterValues("var")
Any solutions for the above though?
Solution
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.
OTHER TIPS
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow