JavaEE + BootStrap 實現分頁邏輯

一、項目準備

  1. 準備一張單表,以學生爲例,需要如下列,id,sname,sage,sgender
  2. index.jsp 用於跳轉頁面,second.jsp 用於顯示分頁查詢的數據
  3. getAllServlet 用於查詢分頁數據,並返回給前端

二、數據庫準備

我使用的 mysql 數據庫,數據庫版本是 5.7,然後插入一些隨機數據用於測試使用,因爲要用到分頁查詢,所以我們使用 sql 中的 limit 關鍵字指定查詢的頁數
select * from student limit ?,?

下面是數據庫中所有的測試數據
在這裏插入圖片描述

三、視圖界面編寫

  1. index.jsp
    該界面僅僅是作爲一箇中轉界面,用於對後端的 Servlet 發送一個請求
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
	<!-- 使用 a 標籤默認發起的是一個 get 請求,我們攜帶一個 pageNo 參數,代表從第幾頁開始查詢,和數據庫中 查詢語句 limit ?,? 第一個 ? 相互對應 -->
    <a href="GetAllServlet?pageNo=1">學生數據</a>
</body>
</html>
  1. second.jsp 數據顯示的界面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>學生頁面分頁實現</title>
    <jsp:include page="base.jsp"/> <!-- 這裏麪包含了 BootStrap 的相關庫 -->
</head>
<body>
<div class="container">
    <table class="table table-striped table-bordered text-center table-hover table-condensed" style="margin-top: 20px;">
        <thead>
        <tr>
            <td>學號</td>
            <td>姓名</td>
            <td>年齡</td>
            <td>班級</td>
        </tr>
        </thead>
        <tbody>
        <!-- 使用 JSTL 中的 c:forEach 語法把頁面渲染處來 -->
        <c:forEach var="list" items="${list}">
            <tr>
                <td>${list.getStuId()}</td>
                <td>${list.getStuName()}</td>
                <td>${list.getStuAge()}</td>
                <td>${list.getClassz()}</td>
            </tr>
        </c:forEach>
        </tbody>
    </table>
    <!-- 分頁部分 -->
    <nav style="align-content: center">
        <ul id="pagination" class="pagination">
            <c:choose>
                <c:when test="${pageNo>1}">
                    <li class="page-item"><a class="page-link" href="GetAllServlet?pageNo=${pageNo-1}">上一頁</a></li>
                </c:when>
                <c:otherwise>
                    <li class="page-item disabled"><a class="page-link" href="#">上一頁</a></li>
                </c:otherwise>
            </c:choose>
                    &nbsp;&nbsp;
                    <li class="page-item"><a class="page-link" href=GetAllServlet?pageNo=<%=1%>"><%=1%></a></li>
                    &nbsp;&nbsp;
                     <li class="page-item disabled"><a class="page-link" href="#">...</a></li>
                     &nbsp;&nbsp;
                    <li class="page-item"><a class="page-link" href="GetAllServlet?pageNo=${pageCount}">${pageCount}</a></li>
                    &nbsp;&nbsp;
            <c:choose>
                <c:when test="${pageNo<pageCount}">
                    <li class="page-item"><a class="page-link" href="GetAllServlet?pageNo=${pageNo+1 }">下一頁</a></li>
                </c:when>
                <c:otherwise>
                    <li class="page-item disabled"><a class="page-link" href="#">下一頁</a></li>
                </c:otherwise>
            </c:choose>
        </ul>
    </nav>
</div>
</body>
</html>

四、後臺處理

4.1 封裝 BaseDao

import java.sql.*;

public class BaseDao {
    private String Driver = "com.mysql.jdbc.Driver";
    private static final String URL = "jdbc:mysql://localhost:3306/studentmanagementsystem?useUnicode=true&characterEncoding=utf8";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "root";
    private Connection con = null;

    // 獲取連接
    public PreparedStatement getConnect(String sql) throws SQLException {
        PreparedStatement ps = null;

        try {
            Class.forName(Driver);
            con = DriverManager.getConnection(URL,USERNAME,PASSWORD);
            ps = con.prepareStatement(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ps;
    }

    // 關閉連接
    public void closed(PreparedStatement ps, ResultSet set) throws SQLException {
        if (ps!=null) {
            ps.close();
        }
        if (set!=null) {
            set.close();
        }
        if (con!=null) {
            con.close();
        }
    }

}

4.2 對應的學生實體類

和數據庫中的 student 表的列一一對應

public class Student {
    private String stuId;
    private String stuName;
    private int stuAge;
    private String classz; // 學生所在 年級 班級

    public Student(String stuId, String stuName, int stuAge, String classz) {
        this.stuId = stuId;
        this.stuName = stuName;
        this.stuAge = stuAge;
        this.classz = classz.toString();
    }
	// getter setter 省略
}

4.3 分頁後臺邏輯 GetAllServlet

這裏接收一個前端穿過來的 pageNo,默認傳值爲 1,,這裏面還有幾個特殊的參數要特別說明一下

  1. pageNo 代表查詢第幾列數據
  2. pageSize:每頁要展示多少條數據,也就是 limit ?,? 中的第二個值(固定值)
  3. count:代表數據庫中總記錄數,這個是需要我們在數據庫中 查詢總共有多少條記錄(select count(*) from student)
  4. pageCount: 當前頁面要展示的數據的條數
import cn.gorit.entity.Student;
import cn.gorit.util.BaseDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.text.Style;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

// 分頁顯示數據
@WebServlet("/GetAllServlet")
public class GetAllServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        // 封裝 BaseDao,簡化 JDBC 操作
        BaseDao db = new BaseDao();
        HttpSession session = request.getSession();
        int pageNo = 1; // 默認給一個 pagNo 爲 1
        String str = request.getParameter("pageNo");
        str.replace("\"", "");
        System.out.println(str);
        if (str != null) {
            pageNo = Integer.valueOf(str);
        }

        int pageSize = 5; // 每頁固定的展示數目
        int count = 0; // 求出最大條數
        try {
            PreparedStatement ps = db.getConnect("select count(*) from student");
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                count = rs.getInt(1);
            }
            db.closed(ps,rs);
        } catch (SQLException e) {
            e.printStackTrace();
        }

//        System.out.println(count);

        //每頁顯示的條數
        int pageCount = 0;
        if (count%pageSize == 0) {
            pageCount = count/pageSize;

        } else {
            pageCount = count/pageSize+1;

        }
        
        PreparedStatement ps = null;
        ResultSet rs = null;
        ArrayList<Student> list = new ArrayList<Student>(); // 將學生信息存儲到 列表中
        try {
            ps = db.getConnect("select * from student limit ?,?");
            ps.setInt(1,pageSize*(pageNo-1));
            ps.setInt(2,pageSize);
            rs = ps.executeQuery();
            while (rs.next()) {
                list.add(new Student(rs.getString(1),rs.getString(2),rs.getInt(3),rs.getString(4)));
            }
            db.closed(ps,rs);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        session.setAttribute("pageNo",pageNo);
        session.setAttribute("pageCount",pageCount);
        session.setAttribute("list",list);
        response.sendRedirect("second.jsp");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

五、運行效果

第一頁
在這裏插入圖片描述
第三頁
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章