Sending HTML form data array to JSP/Servlet
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:
Steve
Updated on July 17, 2022Comments
-
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 almost 12 yearsInteresting... and good to know. Then this begs the next question: Can you have 2 dimensional arrays in Java? Like
car[0][make]
? -
BalusC almost 12 yearsYou'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 almost 12 yearsI 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 almost 12 yearsThen 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.