記錄學習 MVC 架構下「查詢所有學生資訊」的完整流程,從請求發起到頁面渲染。
Student 實體、StudentDao 資料存取)test.jsp 發起請求、student.jsp 顯示結果)ListAllStudentServlet)流程:瀏覽器 → Servlet → Dao 查詢 DB → 封裝 List<Student> → request.setAttribute → forward 到 JSP → JSTL/EL 渲染。
src/ ├── com.example.entity.Student ├── com.example.dao.StudentDao ├── com.example.servlet.ListAllStudentServlet WebContent/ ├── test.jsp ├── student.jsp
public class Student {
private String studentId;
private String name;
private String idCard;
private String sex;
private int age;
private int grade;
// 建構子、Getter/Setter、toString 省略
}
public class StudentDao {
public List<Student> getAll() {
List<Student> list = new ArrayList<>();
String sql = "SELECT studentId, name, idCard, sex, age, grade FROM student";
ResultSet rs = null;
try {
rs = DBConnection.executeQuery(sql); // 自訂工具類
while (rs.next()) {
Student s = new Student(
rs.getString(1), rs.getString(2), rs.getString(3),
rs.getString(4), rs.getInt(5), rs.getInt(6)
);
list.add(s);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeQuietly(rs);
}
return list;
}
}
@WebServlet("/listAllStudent")
public class ListAllStudentServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
StudentDao dao = new StudentDao();
List<Student> students = dao.getAll();
req.setAttribute("students", students);
req.getRequestDispatcher("/student.jsp").forward(req, resp);
}
}
<a href="listAllStudent">查看所有學生</a>
<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %>
<table>
<tr><th>學號</th><th>姓名</th><th>身分證</th><th>性別</th><th>年齡</th><th>年級</th></tr>
<c:forEach items="${students}" var="stu">
<tr>
<td>${stu.studentId}</td>
<td>${stu.name}</td>
<td>${stu.idCard}</td>
<td>${stu.sex}</td>
<td>${stu.age}</td>
<td>${stu.grade}</td>
</tr>
</c:forEach>
</table>
注意:原文使用 Scriptlet <% ... %> 迭代,現代最佳實踐改用 JSTL <c:forEach> + EL,分離視圖邏輯。
錯誤:The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "Server key"
原因:JDK 與 SQL Server 驅動之間的加密協議/金鑰不匹配。
解決:
bcprov-jdk15on-1.54.jar、bcprov-ext-jdk15on-1.54.jarJDK_HOME/jre/lib/ext/JDK_HOME/jre/lib/security/java.security,將 security.provider.1 改為 org.bouncycastle.jce.provider.BouncyCastleProvider參考:CSDN 解決方案
DBConnection 封裝連線獲取/關閉,減少樣板碼。