Students2025項目(一)
原始Servlet+JSP架構項目初步搭建
jsp項目已被淘汰,在此學習目的是了解未來學習的新技術的底層原理
項目結構:
項目結構介紹:
目前階段只完成了初始化的后端搭建,實現從本地數據庫獲取數據在瀏覽器顯示
項目大體運行流程為Global->StudentServlet->StudentService->StudentDao,StudentDao層層將獲取的數據回傳一直到StudentServlet,然后請求轉發到list.jsp在jsp頁面中通過JSEL讀入提前寫好的html表格(model的Student類為數據模型,存放類的屬性和get、set方法)
接下來按項目大體運行流程的順序介紹各部分
Global
package com.example.common;import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.SimpleDriverDataSource;
import javax.sql.DataSource;
import java.sql.Driver;
import java.sql.SQLException;
import java.util.Date;public class Global {//驅動名private static final String JDBC_DRIVER="com.mysql.cj.jdbc.Driver";
// 數據庫鏈接字符串private static final String JDBC_URL="jdbc:mysql://localhost:3306/students2025?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true";private static final String JDBC_USERNAME="root";private static final String JDBC_PASSWORD="123456";//獲取數據源 數據庫連接池private static DataSource dataSource = null;//獲取數據源 數據庫連接池public static DataSource getDataSource() throws SQLException {if (dataSource==null){Driver driver = new com.mysql.cj.jdbc.Driver();dataSource = new SimpleDriverDataSource(driver,JDBC_URL,JDBC_USERNAME,JDBC_PASSWORD);}return dataSource;}//spring提供的jdbc模板操作類public static JdbcTemplate getJdbcTemplate() {try {return new JdbcTemplate(getDataSource());} catch (SQLException e) {throw new RuntimeException(e);}}
}
作用:
初始化數據庫連接,創建數據庫連接池,如果連接池為空,就按參數新建一個連接,JdbcTemplate 是 Spring JDBC 模塊的核心類,通過get數據源創建 JdbcTemplate 實例,在StudentDao中被調用
數據庫連接池:
用于在應用程序啟動時創建一定數量的數據庫連接,并將這些連接保存在一個"池"中,供應用程序隨時取用。當應用程序需要與數據庫交互時, 不是新建一個連接,而是從連接池中獲取一個空閑連接,使用完畢后再歸還給連接池,而不是關閉它。
StudentService
package com.example.servlet;import com.example.model.Student;
import com.example.service.impl.StudentServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;import java.io.IOException;
import java.util.List;@WebServlet("/admin/student/*")
public class StudentServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String action = req.getPathInfo();if("/list".equals(action)){StudentServiceImpl studentService =new StudentServiceImpl();List<Student> students = studentService.findAll();//放到請求域req.setAttribute("students",students);req.getRequestDispatcher("/WEB-INF/jsp/student/list.jsp").forward(req,resp);}}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//todo}
}
作用:
處理http請求, 用戶訪問URL:
/admin/student/list,if判斷用戶輸入地址是不是/admin/student//list,如果是,創建StudentServiceImpl對象,調用findall方法,將獲取到的數據存到List中,然后將名為students的集合存放到request請求域中,然后request調用請求轉發方法將students轉發到/WEB-INF/jsp/student/list.jsp。
StudentServiceImpl和StudentService
package com.example.service.impl;import com.example.dao.impl.StudentDaoImpl;
import com.example.model.Student;
import com.example.service.StudentService;import java.util.List;public class StudentServiceImpl implements StudentService {@Overridepublic List<Student> findAll() {StudentDaoImpl studentDaoImpl = new StudentDaoImpl();return studentDaoImpl.findAll();}
}
package com.example.service;import com.example.model.Student;import java.util.List;public interface StudentService {//查詢所有學生List<Student> findAll();
}
StudentServiceImpl是StudentService的實現,StudentService接口定義了findAll的抽象方法,
StudentServiceImpl實現這個抽象方法,在方法中創建new
StudentDaoImpl()對象,調用了studentDaoImpl.findAll()方法,在studentDaoImpl.findAll()的方法體內真正實現了查找功能實現。
StudentDaoImpl和 StudentDao
package com.example.dao.impl;import com.example.common.Global;
import com.example.dao.StudentDao;
import com.example.model.Student;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
//數據倉庫
public class StudentDaoImpl implements StudentDao {@Overridepublic List<Student> findAll() {JdbcTemplate jdbcTemplate= Global.getJdbcTemplate();String sql ="select id,stu_id,name,sex,birthday,pinyin,phone,email,qq,wechat from t_student limit 20";RowMapper<Student> rowMapper =new BeanPropertyRowMapper<>(Student.class);List<Student> students = jdbcTemplate.query(sql, rowMapper);return students;}
}
package com.example.dao;import com.example.model.Student;import java.util.List;public interface StudentDao {List<Student> findAll();
}
作用:負責與數據庫直接交互
StudentDao 的findAll方法是這幾個類層層調用的最底層的findAll抽象方法,也就是上面介紹的findAll方法層層調用,最終都是調的這個findAll方法,首先獲取JdbcTemplate實例通過Global.getJdbcTemplate()獲取Spring的JdbcTemplate,JdbcTemplate是Spring對JDBC的核心封裝,簡化了數據庫操作,然后定義sql查詢,查詢t_student表中的20條記錄,然后創建RowMapper,BeanPropertyRowMapper是Spring提供的實現類,自動將結果集的列映射到Student對象的屬性,也就是將結果集列名轉換為屬性名(stu_id → stuId),jdbcTemplate.query(sql, rowMapper)執行sql語句存到集合里并返回
Student
package com.example.model;import lombok.Getter;
import lombok.Setter;import java.time.LocalDate;
//這兩個注解相當于getset方法
@Getter
@Setter
public class Student {private Integer id;private String stuId;private String name;private String pinyin;private String sex;private String qq;private String email;private String phone;private String wechat;private LocalDate birthday;}
作用:
定義了Student類的數據模型,屬性,通過@Getter和@Setter注解簡便實現get和set方法
剩余流程分析
在StudentDaoImpl里將查詢結果list列表student結果進行層層返回,最終到StudentServlet的List students = studentService.findAll();中,也是存到list集合里,然后通過 req.setAttribute(“students”,students);放到請求域中,再請求轉發到
“/WEB-INF/jsp/student/list.jsp”
在list.jsp中有如下代碼:
<%--Created by IntelliJ IDEA.User: LenovoDate: 2025/7/24Time: 15:16To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--引入標簽庫,固定語法--%>
<%@taglib prefix="c" uri="jakarta.tags.core" %>
<html>
<head><title>Title</title>
</head>
<body>
<table id="tbl"><thead><tr><th>ID</th><th>學號</th><th>姓名</th><th>拼音</th><th>性別</th><th>出生日期</th><th>手機號</th><th>微信號</th><th>郵箱</th><th>QQ</th></tr></thead><tbody>
<%-- 遍歷名為"students"的集合(由Servlet通過req.setAttribute("students",students)設置)--%><c:forEach items="${students}" var="s"><tr><td>${s.id}</td><td>${s.stuId}</td><td>${s.name}</td><td>${s.pinyin}</td><td>${s.sex}</td><td>${s.birthday}</td><td>${s.phone}</td><td>${s.wechat}</td><td>${s.email}</td><td>${s.qq}</td></tr></c:forEach></tbody>
</table>
</body>
</html>
<c:forEach items=“${students}” var=“s”>遍歷傳入的名為student的list集合,獲取各個屬性放入提前寫好的表格中