Reputation: 2183
I'm trying to update information using a dynamically generated form. Obviously I could do the following and everything would be simple:
<%
String[] names = {"John", "Paula", "Mark", "Maria"};
for(String name: names)
%>
<form method="post" action="SavePersonalDetails">
<p><%= name %>
<input type="text" name="age">
<input type="submit" value="Save">
</form>
<%
}
%>
But I can't figure a non-messy way to do the same by only presenting the user with one submit button as in the following case:
<form method="post" action="SavePersonalDetails">
<%
String[] names = {"John", "Paula", "Mark", "Maria"};
for(String name: names)
%>
<p><%= name %>
<input type="text" name="age">
<%
}
%>
<input type="submit" value="Save">
</form>
Is there a way to do this?
Upvotes: 0
Views: 779
Reputation: 76
Using the second way you can obtain from the getter
String[] ages = request.getParameterValues("age");
an array of age.
The position of the value in the array is the same used in the page, so you must have the same names
array in the servlet to associate ages to the right person.
The jsp code seems to be right
Upvotes: 1
Reputation: 160311
You need to associate param names with the user in question. There are any number of ways to do that, it's typical to embed an ID or qualifier in the input element name somehow, e.g.,
<input type="text" name="age[0]">
<input type="text" name="age[John]">
Or
<input type="text" name="age_0">
<input type="text" name="age_John">
Or
<input type="text" name="age['John']">
And so on.
Then you iterate over the parameters looking for names that startWith
the parameter in question, e.g., age_
. You split the param name on underscores, or pull out the indexed notation, etc. so you know who's age is held in that parameter's value.
This avoids having to rely on parameter ordering, and makes it easier to manipulate things with JavaScript as well: each element has a unique, non-positional identifier.
Upvotes: 0