收集多个动态 HTML 输入的提交值并将其保存回 servlet [英] Collect and save submitted values of multiple dynamic HTML inputs back in servlet

查看:14
本文介绍了收集多个动态 HTML 输入的提交值并将其保存回 servlet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用 JSTL 以 JSP 形式显示 bean 的 ArrayList,方法是遍历列表并在 HTML 输入标记中输出 bean 属性.

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>

如何编写 JSP 代码,以便在页面提交时更新的值位于 ArrayList 的适当项目中?

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?

推荐答案

鉴于这个简化的模型:

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

如果 ${items}List:

<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>

(注意 fn:escapeXml() 作为 XSS 的重要性攻击预防)

因此,基本上,您需要将项目的唯一标识符设置为每行中的隐藏输入字段,如上面的代码片段所示:

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}" />

并且您应该依次使用此 id 作为同一行中所有输入字段的 name 的后缀,例如:

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}" ... />

在servlet中,您可以收集 来自 request.getParameterValues() 的所有行.只需循环它,然后通过 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);
    // ...
}

你也可以在没有 id 的情况下完成这一切,并按名称获取所有输入作为数组,就像 name=foo"request.getParameterValues("foo"),但是请求参数的顺序不在您的控制之下.HTML 表单会按顺序发送它,但最终用户可以轻松地操纵顺序.

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.

这里不需要 JavaScript 混乱.

No need for JavaScript mess here.

这篇关于收集多个动态 HTML 输入的提交值并将其保存回 servlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆