使用 servlets 打开 jsp 使用 id 编辑页面
Using servlets to open jsp edit page using id
我对使用 Servlet 和 JSP 还很陌生,我正在尝试获取一个列出所有用户的 JSP 页面,以重定向到编辑表单 jsp,具体取决于在用户 ID 上,列出所有用户的 JSP 页面使用迭代器显示来自我的 JDBC table 的数据,但我似乎无法弄清楚如何单独为编辑 link 以便它可以加载带有该用户数据的编辑表单,我们将不胜感激。
这里是 jsp 页面的当前代码,用于列出所有学生
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="java.util.*" import="model.Student"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, intial-scale=1 shink-to-fit=yes">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
integrity="sha384-..." crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-dark bg-primary pd-8">
<a class="navbar-brand"> ...University</a>
</nav>
<div class="container-fluid">
<div class="container">
<div class="form container-fluid p-4">
<a href="<%=request.getContextPath()%>/new" class="btn btn-success" >Add
Student</a>
</div>
<br>
<!--Assigning ArrayList object containing student data to the local object -->
<% ArrayList<Student> studentList = (ArrayList) request.getAttribute("listStudents"); %>
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<!-- data from table displayed using iterator-->
<%
if(request.getAttribute("listStudents") != null) {
Iterator<Student> iterator = studentList.iterator();
while(iterator.hasNext()) {
Student studentDetails = iterator.next();
%>
<tr><td><%=studentDetails.getId()%></td>
<td><%=studentDetails.getName()%></td>
<td><%=studentDetails.getEmail()%></td>
<td><a href="<%=request.getContextPath()%>/edit?id=<%=studentDetails.getId()%>">Update</a> <!-- id assigned to edit link-->
<a href="<%=request.getContextPath()%>/delete?id=<%=studentDetails.getId()%>">Delete</a></td> <!-- id assigned to delete link-->
</tr>
<%
}
}
%>
</tbody>
</table>
</div>
</div>
</body>
</html>
然后应该将 id 值分配给 servlet 中的一个值,该值用于 select 来自 table 的特定学生,当调用编辑时
这是我的部分 servlet 代码:
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import dao.StudentDao;
import model.Student;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
public class StudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private StudentDao studentDao;
public StudentServlet() {
this.studentDao = new StudentDao();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String sPath = request.getServletPath();
//switch statement to call appropriate method
switch (sPath) {
case "/new":
try {
showNewForm(request, response);
} catch (ServletException | IOException e) {
e.printStackTrace();
}
break;
case "/insert":
try {
insertStudent(request, response);
} catch (SQLException | IOException e) {
e.printStackTrace();
}
break;
case "/delete":
try {
deleteStudent(request, response);
} catch (SQLException | IOException e) {
e.printStackTrace();
}
break;
case "/update":
try {
updateStudent(request, response);
} catch (SQLException | IOException e) {
e.printStackTrace();
}
break;
case "/edit":
try {
editStudent(request, response);
} catch (ServletException | IOException e) {
e.printStackTrace();
}
break;
default:
try {
listAllStudents(request, response); //home page = .../week04/StudentServlet
} catch (ServletException | IOException | SQLException e) {
e.printStackTrace();
}
break;
}
}
private void editStudent(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
Student currentStudent = studentDao.selectStudent(id);
System.out.println(currentStudent);
RequestDispatcher dispatch = request.getRequestDispatcher("student-form.jsp");
request.setAttribute("student", currentStudent);
dispatch.forward(request, response);
}
private void listAllStudents(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
List<Student> allStudents = studentDao.selectAllStudents();
request.setAttribute("listStudents", allStudents);
RequestDispatcher dispatch = request.getRequestDispatcher("student-list.jsp");
dispatch.forward(request, response);
}
}
这是我的 DAO,以防我没有正确配置它:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import model.Student;
public class StudentDao {
private String jdbcURL = "jdbc:mysql://localhost:3308/xyzuniversity";
private String jdbcUsername = "User";
private String jdbcPassword = "password";
private static final String SELECT_STUDENT_ID = "SELECT name, email FROM student WHERE id =?";
protected Connection getConnection() {
Connection connection = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(jdbcURL, jdbcUsername, jdbcPassword);
}catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
return connection;
}
public Student selectStudent(int id) {
Student student = null;
try {
Connection connection = getConnection();
PreparedStatement prepStatement = connection.prepareStatement(SELECT_STUDENT_ID);
prepStatement.setInt(1, id);
ResultSet rSet = prepStatement.executeQuery();
while(rSet.next()) {
String name = rSet.getString("name");
String email = rSet.getString("email");
student = new Student(id, name, email);
}
} catch (SQLException e) {
e.printStackTrace();
}
return student;
}
最后是应该显示的 jsp 表单
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, intial-scale=1 shink-to-fit=yes">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
integrity="sha384..." crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-dark bg-primary pd-8">
<a class="navbar-brand"> XYZ University</a>
</nav>
<div class="container col-md-5 p-4">
<div class="card">
<div class="card-body">
<% if (request.getAttribute("student") != null) { %>
<!-- form display depends on whether there is data in the table -->
<form action="<%=request.getContextPath()%>/update" method="post">
<% } else { %>
<form action="<%=request.getContextPath()%>/insert" method="post">
<% } %>
<div>
<h2>
<% if (request.getAttribute("student") != null) { %>
Edit Student
<% } else { %>
Add New Student
<% } %>
</h2>
</div>
<% if (request.getAttribute("student") != null) { %>
<input type="hidden" name="id" value="<%=request.getAttribute("student.id") %>" />
<% } %>
<fieldset class="form-group">
<legend>Name</legend>
<% if (request.getAttribute("student") != null) { %>
<input type="text" value="<%=request.getAttribute("student.name") %>" class="form-control" name="name" required="required">
<% } else { %>
<input type="text" value="" class="form-control" name="name" required="required">
<% } %>
</fieldset>
<fieldset class="form-group">
<legend>Email</legend>
<% if (request.getAttribute("student") != null) { %>
<input type="text" value="<%=request.getAttribute("student.email") %>" class="form-control" name="email">
<% } else { %>
<input type="text" value="" class="form-control" name="email">
<% } %>
</fieldset>
<button type="submit" class="t-3 btn btn-success">Save</button>
</form>
</div>
</div>
</div>
</body>
</html>
我假设我通过将编辑 url 设置为 href="<%=request.getContextPath()%>/edit?id=<%=studentDetails.getId 获得了 id 值()%>" 但表单以空值打开,我不知道哪里出错了,也不知道现在如何分配值
真的不知道现在该怎么办,我已经尝试寻找解决方案,但 none 似乎对我的问题有所帮助。如有任何帮助,我们将不胜感激。
问题是您的 request
属性名称是 student
request.setAttribute("student", currentStudent);
但是您的属性查找代码正在寻找 student.id
,然后 returns null
.
<input type="hidden" name="id" value="<%=request.getAttribute("student.id") %>" />
因此,您需要先获取 属性,然后获取其 属性 以将表单 <input>
填充为
<input type="hidden" name="id" value="<%= ((Student) request.getAttribute("student")).getId() %>" />
<input type="text" name="name" value="<%= ((Student) request.getAttribute("student")).getName() %>" ... />
<input type="text" name="email" value="<%= ((Student) request.getAttribute("student")).getEmail() %>" ... />
request.getAttribute()
方法的 return 类型是 Object
,因此,在使用 getter 访问属性之前需要强制转换为 Student
。这意味着 JSP 页面也需要一个 import
指令。
<%@ page import="model.Student" %>
但是,我建议使用 JSP EL 表达式语言 语法将这些查找缩短为
<input type="hidden" name="id" value="${student.id}" />
<input type="text" name="name" value="${student.name}" class="form-control" required="required" />
<input type="text" name="email" value="${student.email}" class="form-control" />
这看起来更简洁,更具可读性,无需类型转换并优雅地处理 null
值。您甚至不需要所有这些 null
检查,因为如果 student
属性为 null
.
,value
将自动设置为 ""
所以,你所有的 form-group
s
<fieldset class="form-group">
<legend>First Name</legend>
<% if (request.getAttribute("student") != null) { %>
<input type="text" value="${student.firstname}" class="form-control"
name="firstname" required="required">
<% } else { %>
<input type="text" value="" class="form-control" name="firstname" required="required">
<% } %>
</fieldset>
可以使用 EL 简化为几行。
<fieldset class="form-group">
<legend>First Name</legend>
<input type="text" value="${student.firstname}" class="form-control"
name="fistname" required="required">
</fieldset>
我对使用 Servlet 和 JSP 还很陌生,我正在尝试获取一个列出所有用户的 JSP 页面,以重定向到编辑表单 jsp,具体取决于在用户 ID 上,列出所有用户的 JSP 页面使用迭代器显示来自我的 JDBC table 的数据,但我似乎无法弄清楚如何单独为编辑 link 以便它可以加载带有该用户数据的编辑表单,我们将不胜感激。
这里是 jsp 页面的当前代码,用于列出所有学生
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="java.util.*" import="model.Student"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, intial-scale=1 shink-to-fit=yes">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
integrity="sha384-..." crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-dark bg-primary pd-8">
<a class="navbar-brand"> ...University</a>
</nav>
<div class="container-fluid">
<div class="container">
<div class="form container-fluid p-4">
<a href="<%=request.getContextPath()%>/new" class="btn btn-success" >Add
Student</a>
</div>
<br>
<!--Assigning ArrayList object containing student data to the local object -->
<% ArrayList<Student> studentList = (ArrayList) request.getAttribute("listStudents"); %>
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<!-- data from table displayed using iterator-->
<%
if(request.getAttribute("listStudents") != null) {
Iterator<Student> iterator = studentList.iterator();
while(iterator.hasNext()) {
Student studentDetails = iterator.next();
%>
<tr><td><%=studentDetails.getId()%></td>
<td><%=studentDetails.getName()%></td>
<td><%=studentDetails.getEmail()%></td>
<td><a href="<%=request.getContextPath()%>/edit?id=<%=studentDetails.getId()%>">Update</a> <!-- id assigned to edit link-->
<a href="<%=request.getContextPath()%>/delete?id=<%=studentDetails.getId()%>">Delete</a></td> <!-- id assigned to delete link-->
</tr>
<%
}
}
%>
</tbody>
</table>
</div>
</div>
</body>
</html>
然后应该将 id 值分配给 servlet 中的一个值,该值用于 select 来自 table 的特定学生,当调用编辑时
这是我的部分 servlet 代码:
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import dao.StudentDao;
import model.Student;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
public class StudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private StudentDao studentDao;
public StudentServlet() {
this.studentDao = new StudentDao();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String sPath = request.getServletPath();
//switch statement to call appropriate method
switch (sPath) {
case "/new":
try {
showNewForm(request, response);
} catch (ServletException | IOException e) {
e.printStackTrace();
}
break;
case "/insert":
try {
insertStudent(request, response);
} catch (SQLException | IOException e) {
e.printStackTrace();
}
break;
case "/delete":
try {
deleteStudent(request, response);
} catch (SQLException | IOException e) {
e.printStackTrace();
}
break;
case "/update":
try {
updateStudent(request, response);
} catch (SQLException | IOException e) {
e.printStackTrace();
}
break;
case "/edit":
try {
editStudent(request, response);
} catch (ServletException | IOException e) {
e.printStackTrace();
}
break;
default:
try {
listAllStudents(request, response); //home page = .../week04/StudentServlet
} catch (ServletException | IOException | SQLException e) {
e.printStackTrace();
}
break;
}
}
private void editStudent(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
Student currentStudent = studentDao.selectStudent(id);
System.out.println(currentStudent);
RequestDispatcher dispatch = request.getRequestDispatcher("student-form.jsp");
request.setAttribute("student", currentStudent);
dispatch.forward(request, response);
}
private void listAllStudents(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
List<Student> allStudents = studentDao.selectAllStudents();
request.setAttribute("listStudents", allStudents);
RequestDispatcher dispatch = request.getRequestDispatcher("student-list.jsp");
dispatch.forward(request, response);
}
}
这是我的 DAO,以防我没有正确配置它:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import model.Student;
public class StudentDao {
private String jdbcURL = "jdbc:mysql://localhost:3308/xyzuniversity";
private String jdbcUsername = "User";
private String jdbcPassword = "password";
private static final String SELECT_STUDENT_ID = "SELECT name, email FROM student WHERE id =?";
protected Connection getConnection() {
Connection connection = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(jdbcURL, jdbcUsername, jdbcPassword);
}catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
return connection;
}
public Student selectStudent(int id) {
Student student = null;
try {
Connection connection = getConnection();
PreparedStatement prepStatement = connection.prepareStatement(SELECT_STUDENT_ID);
prepStatement.setInt(1, id);
ResultSet rSet = prepStatement.executeQuery();
while(rSet.next()) {
String name = rSet.getString("name");
String email = rSet.getString("email");
student = new Student(id, name, email);
}
} catch (SQLException e) {
e.printStackTrace();
}
return student;
}
最后是应该显示的 jsp 表单
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, intial-scale=1 shink-to-fit=yes">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
integrity="sha384..." crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-dark bg-primary pd-8">
<a class="navbar-brand"> XYZ University</a>
</nav>
<div class="container col-md-5 p-4">
<div class="card">
<div class="card-body">
<% if (request.getAttribute("student") != null) { %>
<!-- form display depends on whether there is data in the table -->
<form action="<%=request.getContextPath()%>/update" method="post">
<% } else { %>
<form action="<%=request.getContextPath()%>/insert" method="post">
<% } %>
<div>
<h2>
<% if (request.getAttribute("student") != null) { %>
Edit Student
<% } else { %>
Add New Student
<% } %>
</h2>
</div>
<% if (request.getAttribute("student") != null) { %>
<input type="hidden" name="id" value="<%=request.getAttribute("student.id") %>" />
<% } %>
<fieldset class="form-group">
<legend>Name</legend>
<% if (request.getAttribute("student") != null) { %>
<input type="text" value="<%=request.getAttribute("student.name") %>" class="form-control" name="name" required="required">
<% } else { %>
<input type="text" value="" class="form-control" name="name" required="required">
<% } %>
</fieldset>
<fieldset class="form-group">
<legend>Email</legend>
<% if (request.getAttribute("student") != null) { %>
<input type="text" value="<%=request.getAttribute("student.email") %>" class="form-control" name="email">
<% } else { %>
<input type="text" value="" class="form-control" name="email">
<% } %>
</fieldset>
<button type="submit" class="t-3 btn btn-success">Save</button>
</form>
</div>
</div>
</div>
</body>
</html>
我假设我通过将编辑 url 设置为 href="<%=request.getContextPath()%>/edit?id=<%=studentDetails.getId 获得了 id 值()%>" 但表单以空值打开,我不知道哪里出错了,也不知道现在如何分配值
真的不知道现在该怎么办,我已经尝试寻找解决方案,但 none 似乎对我的问题有所帮助。如有任何帮助,我们将不胜感激。
问题是您的 request
属性名称是 student
request.setAttribute("student", currentStudent);
但是您的属性查找代码正在寻找 student.id
,然后 returns null
.
<input type="hidden" name="id" value="<%=request.getAttribute("student.id") %>" />
因此,您需要先获取 属性,然后获取其 属性 以将表单 <input>
填充为
<input type="hidden" name="id" value="<%= ((Student) request.getAttribute("student")).getId() %>" />
<input type="text" name="name" value="<%= ((Student) request.getAttribute("student")).getName() %>" ... />
<input type="text" name="email" value="<%= ((Student) request.getAttribute("student")).getEmail() %>" ... />
request.getAttribute()
方法的 return 类型是 Object
,因此,在使用 getter 访问属性之前需要强制转换为 Student
。这意味着 JSP 页面也需要一个 import
指令。
<%@ page import="model.Student" %>
但是,我建议使用 JSP EL 表达式语言 语法将这些查找缩短为
<input type="hidden" name="id" value="${student.id}" />
<input type="text" name="name" value="${student.name}" class="form-control" required="required" />
<input type="text" name="email" value="${student.email}" class="form-control" />
这看起来更简洁,更具可读性,无需类型转换并优雅地处理 null
值。您甚至不需要所有这些 null
检查,因为如果 student
属性为 null
.
value
将自动设置为 ""
所以,你所有的 form-group
s
<fieldset class="form-group">
<legend>First Name</legend>
<% if (request.getAttribute("student") != null) { %>
<input type="text" value="${student.firstname}" class="form-control"
name="firstname" required="required">
<% } else { %>
<input type="text" value="" class="form-control" name="firstname" required="required">
<% } %>
</fieldset>
可以使用 EL 简化为几行。
<fieldset class="form-group">
<legend>First Name</legend>
<input type="text" value="${student.firstname}" class="form-control"
name="fistname" required="required">
</fieldset>