Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 438
Steve Avatar asked Aug 02 '12 22:08

Steve


People also ask

Can a JSP process HTML form data?

Reading Form Data using JSPJSP handles form data parsing automatically using the following methods depending on the situation: getParameter() − You call request. getParameter() method to get the value of a form parameter.

How does servlet read HTML form data?

The doGet() method in servlets is used to process the HTTP GET requests. So, basically, the HTTP GET method should be used to get the data from the server to the browser. Although in some requests, the GET method is used to send data from the browser to the server also.

Can we read data from a form using JSP?

Reading Form Data using JSPgetParameterValues(): Call this method if the parameter appears more than once and returns multiple values, for example, checkbox. getParameterNames(): Call this method if you want a complete list of all parameters in the current request.


1 Answers

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:

  • Send an Array with an HTTP Get
like image 71
BalusC Avatar answered Oct 19 '22 03:10

BalusC