我有一组单选按钮,每个按钮代表一行,每行有一个Id。我正在使用价值来复合这两者。我的servlet可以处理这个,但我想知道是否有更好的方法将动作与id分开并让servlet接收它们?
<td class="listData"><input type="radio" value="insert-${data.Id}" name="recordIds${data.Id}" id="${data.Id}"/></td>
<td class="listData"><input type="radio" value="update-${data.Id}" name="recordIds${data.Id}" id="${data.Id}"/></td>
<td class="listData"><input type="radio" value="delete-${data.Id}" name="recordIds${data.Id}" id="${data.Id}"/></td>
答案 0 :(得分:2)
正如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>
会给你一张表格
将使用doPost()方法将其输入重定向到servlet
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,您应该单独创建Data类并尝试避免JSP中的Java代码,我只将其用于演示目的