【问题标题】:How I can send parameter to a JSP servlet with a c:forEach form? [duplicate]如何使用 c:forEach 表单向 JSP servlet 发送参数? [复制]
【发布时间】:2020-05-10 13:28:19
【问题描述】:

我在混合 JSP Servlet 和 c:forEach 表单时遇到问题... 问题是无论我的 id 是什么,HTML 表单总是会发送列表中的第一个,称为“name="id"”。 有没有办法获得几个 name="id1", name="id2" ...等等以获得好的?

这里是代码。

    <div id="client-table">
        <form action="gestion-commandes" method="POST">

            <table class="table table-striped">
                <thead class="thead-custom">
                    <tr>
                        <th scope="col">#</th>
                        <th scope="col">NOM</th>
                        <th scope="col">PRENOM</th>
                        <th scope="col">EMAIL</th>
                        <th scope="col">TEL</th>
                        <th scope="col">COMMANDES</th>
                    </tr>
                </thead>
                <tbody class="tbody-custom">

                    <c:forEach items="${clients}" var="client">
                        <tr>
                            <th scope="col">${client.id}<input name="id" value="${client.id}" hidden = "true"></th>
                            <th scope="col">${client.nom}</th>
                            <th scope="col">${client.prenom}</th>
                            <th scope="col">${client.email}</th>
                            <th scope="col">${client.tel}</th>
                            <th scope="col"><button type="submit">Commandes</button>
                            </th>
                        </tr>
                    </c:forEach>
                </tbody>                
            </table>

        </form>
    </div>

</div>

提前谢谢你, 乔斯

【问题讨论】:

  • 您需要获取所有 id 吗?还是只有特定的一个?

标签: html forms jsp servlets foreach


【解决方案1】:

当参数有多个值时,使用request.getParameter("id")将只返回第一个参数值。

您可以使用request.getParameterValues 而不是request.getParameter 来获取所有值,例如:

String[] ids = request.getParameterValues("id");

但是,如果您只想获取一个值,对应于您单击的行,则不能使用隐藏输入,因为所有隐藏输入都将随提交一起发送。

仅获取所选 id 的最直接方法是将其作为按钮的值传递。只有单击的按钮会随提交一起发送。

<button type="submit" name="selected" value="${client.id}">Commandes</button>

并通过以下方式将其放在您的 servlet 上:

String selectedId = request.getParametre("selected");

您将在this answer 中找到标记为重复的问题的更多详细信息。

【讨论】:

  • 我只想使用一个id,我点击的那个。
  • JSP servlet 会读取第一个值,因为它们具有所有相同的参数'name="id"'
  • 对不起,我没有注意循环里面的按钮,所以我误解了你的问题。我编辑了答案,但您会找到关于标记为重复的问题的更详细说明
  • 我解决了这个问题,将
    放在 中,作为列表中的对象创建,而不是一个
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-13
  • 1970-01-01
  • 2016-02-07
  • 2012-06-05
  • 2019-01-07
  • 2013-05-16
  • 1970-01-01
相关资源
最近更新 更多