我正在使用 JSP 和 Servlet 编写一个网站,需要将 JSP 表中的多条记录更新到数据库 MSSQL 中。假设我有一个这样的表:
Post.jsp
<form method="POST" action="PostServlet?action=update">
<table border="1">
<tr>
<th>Post ID</th>
<th>Title</th>
<th>Date</th>
<th>Status</th>
</tr>
<c:forEach var="p" items="${requestScope.list}">
<tr>
<td>${p.id}</td>
<td>${p.title}</td>
<td>${p.date}</td>
<td>
<select name="slStatus">
<option value="approve" selected="true">Approve</option>
<option value="unapprove">Unaprove</option>
</select>
</td>
</tr>
</c:forEach>
<tr><button type="submit" value="Update"></button>
</table>
假设我选择并更改几行中的状态。我应该在 Servlet 中放入什么,以便将表中所有更改的值更新到数据库中?任何帮助表示赞赏。
最佳答案
您应该发送主键值,状态如下:
<form method="POST" action="PostServlet?action=update">
<table border="1">
<tr>
<th>Post ID</th>
<th>Title</th>
<th>Date</th>
<th>Status</th>
</tr>
<c:forEach var="p" items="${requestScope.list}">
<tr>
<td>${p.id}</td>
<td>${p.title}</td>
<td>${p.date}</td>
<td>
<select name="slStatus">
<option value="approve" selected="true">Approve</option>
<option value="unapprove">Unaprove</option>
</select>
<input type="hidden" name="postId" value="${p.id}"/>
</td>
</tr>
</c:forEach>
<tr><button type="submit" value="Update"></button>
</table>
现在,您可以在 servlet 中根据主键值查找并更新状态。 注意:postId 和 slStatus 参数将具有相等长度的数组值(在 servlet 中)。并且在同一索引处,它们将表示一个对象(实体类,即表示数据库表)的各自值。
关于java - jsp更新表中的多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36789360/