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?

3
  • JSP comes to mind. Commented Aug 2, 2012 at 22:04
  • 1
    @Makoto That doesn't address the question, though; JSP doesn't do any type conversion of its own. Commented Aug 2, 2012 at 22:05
  • FYI Java is a word and not an acronym Commented Aug 2, 2012 at 22:08

1 Answer 1

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:

Sign up to request clarification or add additional context in comments.

4 Comments

Interesting... and good to know. Then this begs the next question: Can you have 2 dimensional arrays in Java? Like car[0][make]?
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.
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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.