由於Naga Sai A指出,您不應該在HTML文檔中有重複的id值。所以請確保每個輸入都有唯一的ID。
如果我正確理解了你,你不需要爲你的案例中的每一行數據使用不同的值。你需要不同的名字對他們來說只是:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.Arrays" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Change Data</title>
</head>
<body>
<%!
public class Data {
private int id;
public Data(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
List<Data> dataList = Arrays.asList(new Data(10), new Data(11), new Data(12));
%>
<% request.setAttribute("dataList", dataList); %>
<c:url var="controller" value="/controller"/>
<p>Choose your actions for data</p>
<form action="${controller}" method="POST">
<table>
<thead>
<tr>
<td>insert</td>
<td>update</td>
<td>delete</td>
</tr>
</thead>
<tbody>
<c:forEach var="data" items="${dataList}">
<tr>
<td>
<label for="insert-${data.id}">Insert ${data.id}: </label>
<input type="radio" name="recordIds${data.id}" value="insert" id="insert-${data.id}"/>
</td>
<td>
<label for="update-${data.id}">Update ${data.id}: </label>
<input type="radio" name="recordIds${data.id}" value="update" id="update-${data.id}"/>
</td>
<td>
<label for="delete-${data.id}">Delete ${data.id}: </label>
<input type="radio" name="recordIds${data.id}" value="delete" id="delete-${data.id}"/>
</td>
</tr>
</c:forEach>
</tbody>
</table>
<input type="submit" value="Submit actions">
</form>
</body>
</html>
會給你一個形式
,將其輸入重定向到Servlet與doPost()方法
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Collections.list(request.getParameterNames()).forEach(paramName -> {
if (paramName.startsWith("recordIds")) {
String id = paramName.substring(9, paramName.length());
String action = request.getParameter(paramName);
try {
response.getWriter().println("Selected action for data with id=" + id + " is " + action);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
這打印結果
PS:不這樣定義數據類,the use of scriplets is highly discouraged,您需要單獨創建數據類,並儘量避免在JSP中的Java代碼,我用它僅用於演示目的
語法錯誤,請嘗試爲所有單選按鈕避免使用相同的編號 –
我可以更改它。但它並不能解決我的問題。 – johnsam