Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Associative array request parameter parsing with Java Servlet

Tags:

java

servlets

Is it possible to parse the string keys from a request such as this, with the Java servlet API?

http://localhost:8080/?assocArray[key1]=value1&assocArray[key2]=value2&assocArray[key3]=value3

getParameterValues("assocArray") returns ["value3","value1","value1"]

The ordering of the values in the returned array is not order of the keys (not that it matters)

SOLVED: It is possible, the keys are interpreted as simple global key strings. Java doesn't recognize them as an array. Use regex

like image 853
MetaChrome Avatar asked Aug 06 '11 13:08

MetaChrome


1 Answers

You may have several values for the same parameter name:

http://localhost:8080/?param1=value1&param1=value2&param1=value3

In this case, getParameterValues("param1") will return a String[] containing 3 elements : "value1", "value2" and "value3".

In the example you gave, you defined 3 different parameters : assocArray[key1], assocArray[key2] and assocArray[key3]. The servlet API will consider them as 3 totally different parameters having nothing in common. You thus have to call getParameter("assocArray[key1]") to get "value1", getParameter("assocArray[key2]") to get "value2", etc.

like image 84
JB Nizet Avatar answered Oct 14 '22 09:10

JB Nizet