我是使用Servlet和JSP的新手,我試圖讓一個列出所有用戶的JSP頁面根據用戶ID重定向到一個編輯表單JSP,列出所有用戶的JSP頁面使用一個迭代器來顯示來自我的JDBC表的資料,但我似乎不知道如何為每個用戶的編輯鏈接單獨分配一個值,以便它可以用該用戶的資料加載編輯表單,希望你能幫助。
這里是我的jsp頁面的當前代碼,用于列出所有的學生
。<%@ page language="java"/span> 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="styleheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"。
integrity="sha384-..." crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-dark bg-primary pd-8" >
<a class="navbar-brand"> ...大學</a>。
</nav>
<div class="container-fluid">
<div class="container">
<div class="form container-fluid p-4">
<a href="<%=request.getContextPath()%>/new"/span> class="btn btn-success"/span> >添加
學生</a>
</div>
<br>
<!--將包含學生資料的ArrayList物件分配給本地物件-->
<% ArrayList<Student> studentList = (ArrayList) request.getAttribute("listStudents"/span>); %>
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>Email</th>
<th>行動</th>
</tr>
</thead>
<tbody>
<!-- 使用迭代器顯示表格中的資料-->
<%
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()%>">更新</a> <--分配給編輯鏈接的id-->。
<a href="<%=request.getContextPath()%>/delete? id=<%=studentDetails.getId()%>">洗掉</a></td> <--分配給洗掉鏈接的id-->。
</tr>
<%。
}
}
%>
</tbody>
</table>
</div>
</div>
</body>
</html>
然后id值應該被分配給servlet中的一個值,當編輯被呼叫時,它被用來從表中選擇特定的學生
這里是我的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[/span]。
switch (sPath) {
case "/new"/span>:
try {
showNewForm(request, response);
} catch (ServletException | IOException e) {
e.printStackTrace()。
}
break;
case "/insert"/span>:
try {
insertStudent(request, response);
} catch (SQLException | IOException e) {
e.printStackTrace()。
}
break;
case "/delete"/span>:
try {
deleteStudent(request, response);
} catch (SQLException | IOException e) {
e.printStackTrace()。
}
break;
case "/update"/span>:
try {
updateStudent(request, response);
} catch (SQLException | IOException e) {
e.printStackTrace()。
}
break;
case "/edit"/span>:
try {
editStudent(request, response);
} catch (ServletException | IOException e) {
e.printStackTrace()。
}
break;
default:
try {
listAllStudents(request, response); /home page = .../week04/StudentServletcatch (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"/span>, allStudents)。
RequestDispatcher dispatch = request.getRequestDispatcher("student-list.jsp")。
dispatch.forward(request, response)。
}
}
這是我的DAO,以防我沒有正確地配置它:
這是一個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" /span>。
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"/span>)。
connection = DriverManager.getConnection(jdbcURL, jdbcUsername, jdbcPassword)。
}catch (SQLException | ClassNotFoundException e) {
e.printStackTrace()。
}
return 連接。
}
public Student selectStudent(int id){
Student student = null;
try {
Connection connection = getConnection();
PreparedStatement prepStatement = connection.prepareStatement(SELECT_STUDENT_ID)。
prepStatement.prepStatement(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 學生。
}
最后是應該顯示的jsp表單
<%@ page language="java"/span> 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="styleheet" href="https://cdn.jsdelivr.net/npm/[email protected]/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大學</a>
</nav>
<div class="container col-md-5 p-4"/span>>
<div class="card">
<div class="card-body">
<% if (request.getAttribute("student") != null) { %>
<!--表格的顯示取決于表中是否有資料 -->
<form action="<%=request.getContextPath()%>/update"/span> method="post"/span>>
<% } else { %>
<form action="<%=request.getContextPath()%>/insert"/span> method="post"/span>>
<% } %>
<div>
<h2>
<% if (request.getAttribute("student") != null) { %>
編輯學生
<% } else { %>
添加新的學生
<% } %>
</h2>
</div>
<% if (request.getAttribute("student") != null) {%>
<input type="hidden" name="id" value="<%=request.getAttribute("student.id" ) %> " />
<% } %>
<fieldet class="form-group">
<legend>姓名</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>
<fieldet 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>
我以為我通過將編輯網址設定為 href="<%=request.getContextPath()%>/edit?id=<%=studentDetails.getId()%> "來獲得id值,但表單打開時出現了一個空值,我不知道我哪里出了問題,或者現在該如何分配這個值
。我真的不知道現在該怎么做,我試著搜索解決方案,但似乎都無法解決我的問題,希望能得到幫助。
uj5u.com熱心網友回復:
問題是你的request屬性的名字是student
request.setAttribute("student", currentStudent)。
但是你的屬性查找代碼是在尋找student.id,然后回傳null。
<input type="hidden" name="id" value="<%=request. getAttribute("student.id") %>" />
因此,你需要先獲得屬性,然后再獲得它的屬性來填充你的表單<input>s作為
<input type="hidden" name="id" value="<%=((學生) request. getAttribute("student")).getId() %>" />
<input type="text" name="name" value="<%=((學生)request.getAttribute("student").getName()%> " ... />
<input type="text" name="email" value="<%=((學生) request.getAttribute("student").getEmail() %>" ... />。
request.getAttribute()方法的回傳型別是一個Object,所以,在用getters訪問屬性之前,需要將其轉換為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-groups
<fieldet 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簡化為幾行。
<fieldet class="form-group">
<legend>First Name</legend>
<input type="text" value="${student.firstname}" class="form-control"。
name="fistname" required="required">
</fieldset>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/315167.html
標籤:
