jsp与Dao层合作实现分页功能

发布时间 2023-10-07 09:18:23作者: 千叶落木
  1. studentList.jsp里面加样式居中和分页栏

居中:.pagination {
    text-align: center;
}

 

 

分页栏:

 <div class="pagination">
    <c:if test="${currentPage > 1}">
        <a href="${pageContext.request.contextPath}/ShowStudentServlet?page=${currentPage - 1}">上一页</a>
    </c:if>

    <c:forEach begin="1" end="${totalPages}" var="pageNumber">
        <c:choose>
            <c:when test="${pageNumber == currentPage}">
                <!--判断当前页码是否等于当前页数-->
                <!--相等-->
                <strong>${pageNumber}</strong>
            </c:when>
            <c:otherwise>
                <!--不相等,设置链接地址到当前页码-->
                <a href="${pageContext.request.contextPath}/ShowStudentServlet?page=${pageNumber}">${pageNumber}</a>
            </c:otherwise>
        </c:choose>
    </c:forEach>

    <c:if test="${currentPage < totalPages}">
        <!--判断当前页数是否小于总页数。如果成立,则显示一个链接到下一页的 <a> 元素。-->
        <a href="${pageContext.request.contextPath}/ShowStudentServlet?page=${currentPage + 1}">下一页</a>
    </c:if>
</div>

 

 

创建工具类:Page

package com.cn.util;

public class Page {

        private int currentPage;//当前页
        private int totalPages;//总页数

        public Page(int currentPage, int totalPages) {
            this.currentPage = currentPage;
            this.totalPages = totalPages;
        }

        public int getCurrentPage() {//----------------------------返回当前页数。

            return currentPage;
        }

        public void setCurrentPage(int currentPage) {//--------------设置当前页数。

            this.currentPage = currentPage;
        }

        public int getTotalPages() {//----------------------------返回总页数。

            return totalPages;
        }

        public void setTotalPages(int totalPages) {//------------设置总页数。

            this.totalPages = totalPages;
        }
    }

 

Servlet里面:

 

代码段1

int currentPage = 1;//当前页面
int pageSize = 10;//页面数据条数

String pageParam = request.getParameter("page");
if (pageParam != null && !pageParam.isEmpty()) {
    //pageParam不为空且不为空字符串(null表示空,.isEmpty()表示长度为0判断是否有效)
    currentPage = Integer.parseInt(pageParam);
}

修改:String countSql = "SELECT COUNT(*) FROM student";

代码段2

int totalRecords = resultSet.getInt(1);//总记录(所有数据数)
int totalPages = (int) Math.ceil((double) totalRecords / pageSize);//总页面

String sql = "SELECT * FROM student LIMIT ?, ?";
int offset = (currentPage - 1) * pageSize;
//根据当前页数和每页显示数量计算出偏移量。由于页数从1开始计数,所以需要减去1
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, offset);//偏移量
preparedStatement.setInt(2, pageSize);//每页显示数量
resultSet = preparedStatement.executeQuery();//将结果保存到结果集

代码段3

request.setAttribute("totalPages", totalPages);//总页数
request.setAttribute("currentPage", currentPage);//当前页