Steve
Steve

Reputation: 8640

Sending HTML form data array to JSP/Servlet

I am coming from the PHP world, where any form data that has a name ending in square brackets automatically gets interpreted as an array. So for example:

<input type="text" name="car[0]" />
<input type="text" name="car[1]" />
<input type="text" name="car[3]" />

would be caught on the PHP side as an array of name "car" with 3 strings inside.

Now, is there any way to duplicate that behavior when submitting to a JSP/Servlet backend at all? Any libraries that can do it for you?

EDIT:

To expand this problem a little further:

In PHP,

<input type="text" name="car[0][name]" />
<input type="text" name="car[0][make]" />
<input type="text" name="car[1][name]" />

would get me a nested array. How can I reproduce this in JSP?

Upvotes: 11

Views: 21581

Answers (1)

BalusC
BalusC

Reputation: 1108852

The [] notation in the request parameter name is a necessary hack in order to get PHP to recognize the request parameter as an array. This is unnecessary in other web languages like JSP/Servlet. Get rid of those brackets

<input type="text" name="car" />
<input type="text" name="car" />
<input type="text" name="car" />

This way they will be available by HttpServletRequest#getParameterValues().

String[] cars = request.getParameterValues("car");
// ...

See also:

Upvotes: 11

Related Questions