Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

jsp - Collect and save submitted values of multiple dynamic HTML inputs back in servlet

I am able to display an ArrayList of beans in a JSP form using JSTL by looping through the list and outputting the bean properties in a HTML input tag.

<c:forEach items="${listOfBeans}" var="bean">
  <tr>
    <td><input type="text" id="foo" value="${bean.foo}"/></td>  
    <td><input type="text" id="bar" value="${bean.bar}"/></td>                     
  </tr>
</c:forEach>

How do I code the JSP so that when the page submits then the updated values are in the appropriate item of the the ArrayList?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Given this simplified model:

public class Item {
    private Long id;
    private String foo;
    private String bar;
    // ...
}

Here's how you can do it provided ${items} is List<Item>:

<c:forEach items="${items}" var="item">
    <tr>
        <td>
            <input type="hidden" name="id" value="${item.id}" />
            <input name="foo_${item.id}" value="${fn:escapeXml(item.foo)}" />
        </td>  
        <td>
            <input name="bar_${item.id}" value="${fn:escapeXml(item.bar)}" />
        </td>
    </tr>
</c:forEach>

(note the importance of fn:escapeXml() as XSS attack prevention)

So, basically, you need to set the item's unique identifier as a hidden input field in each row as shown in above snippet:

<input type="hidden" name="id" value="${item.id}" />

And you should in turn use this id as suffix of name of all input fields in the same row such as:

<input name="foo_${item.id}" ... />

In the servlet, you can collect all values of <input type="hidden" name="id" ...> from all rows by request.getParameterValues(). Just loop over it and then grab the individual inputs by id.

for (String id : request.getParameterValues("id")) {
    String foo = request.getParameter("foo_" + id);
    String bar = request.getParameter("bar_" + id);
    // ...
}

You can also do this all without that id and grab all inputs by name as an array like so name="foo" and request.getParameterValues("foo"), but the ordering of request parameters is not under your control. HTML forms will send it in order, but the enduser can easily manipulate the order.

No need for JavaScript mess here.

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...