Sending HTML form data array to JSP/Servlet

20,687

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:

Share:
20,687
Steve
Author by

Steve

Updated on July 17, 2022

Comments

  • Steve
    Steve almost 2 years

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