11

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?

Steve
  • 8,609
  • 6
  • 40
  • 54

1 Answers1

11

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:

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Interesting... and good to know. Then this begs the next question: Can you have 2 dimensional arrays in Java? Like `car[0][make]`? – Steve Aug 02 '12 at 22:10
  • 1
    You'd need to collect them yourself in a loop. JSP/Servlet isn't that high-level as PHP. Better look for more sane ways or just a MVC framework like Spring MVC or JSF so that the model values are automagically updated. – BalusC Aug 02 '12 at 22:12
  • I agree with the framework idea, but that fails in the case that you generate more form fields on the client side. Here is the example I am struggling with: Let's say you have a form that captures an event registration. You get all your standard fields, but can add 0 to 10 guests to your registration. In PHP you could have JS generate a guest[0][firstname] input field for the first guest and a guest[1][firstname] field for the second. Going with a Spring MVC, you would have to account for all 10 guests from the start and submit blank data for all of them. – Steve Aug 02 '12 at 22:56
  • Then use the framework-provided facilities to dynamically create components in server side. Or just collect them yourself in a loop, as said in previous comment. – BalusC Aug 03 '12 at 13:29