我有一个jsp向我展示了一个来自基地的学生名单。对于每个学生,我想要2个按钮 - 编辑和删除。在编辑时单击该请求应重定向到我的servlet控制器,并打开一个新的jsp用于编辑所选学生的数据。在删除时,单击所选学生的删除请求将发送到控制器。现在它看起来像这样:
<%@page import="socnet2.Student"%>
<!-- class Student emulates real student -->
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<jsp:useBean class="socnet2.DAO" id="dao" scope="request"></jsp:useBean>
<p><b>List of all students:</b></p>
<form action="/JSP1/Controler" method="POST">
<jsp:scriptlet>
for (Student s : dao.getAllStudents()) {
</jsp:scriptlet>
<p> <jsp:expression> s.getName() + " " + s.getSurname()</jsp:expression></p>
<input type="submit" name="Edit" value="Edit" />
<input type="submit" name="Delete" value ="Delete"/>
<jsp:scriptlet>
}
</jsp:scriptlet>
</form>
</body>
问题是我无法弄清楚如何将学生与按钮联系起来,当请求被发送到控制器时,可以知道点击了哪个按钮以及选择了哪个学生。我知道我需要为每个学生提供一些独特的ID,但不知道如何创建它......
答案 0 :(得分:4)
我相信Student
已经拥有某种ID。比方说,它有private String id
和适当的getter public String getId()
。
在这种情况下,您只需在生成提交按钮名称时使用此ID:
<input type="submit" name="Edit_<%=s.getId()%>" value="Edit" />
<input type="submit" name="Delete_<%=s.getId()%>" value ="Delete"/>
现在您可以区分服务器端的学生。 或者,您可以为每个学生创建单独的表单,并为每个表单提供其唯一的URL:
<form method="post" url="http://myhost/myapp/students/<%s.getId()%>">