Servlet类
package com.baidu; import cn.hutool.core.util.StrUtil; import javax.servlet.RequestDispatcher; 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 java.io.IOException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @WebServlet("/StudentServlet") public class StudentServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { // 模拟从数据库或其他数据源获取学生列表 ListstudentList = getStudentList(); // 设置分页参数 int pageSize = 5; // 每页显示的记录数 int currentPage = 1; // 当前页数,默认为第一页 // if (StrUtil.isNotEmpty(request.getAttribute("param1").toString())){ // currentPage = (int) request.getAttribute("param1"); // } String pageParam = request.getParameter("page"); if (pageParam != null && !pageParam.isEmpty()) { currentPage = Integer.parseInt(pageParam); } // 计算分页的起始索引和结束索引 int startIndex = (currentPage - 1) * pageSize; int endIndex = Math.min(startIndex + pageSize, studentList.size()); // 获取当前页的学生列表 List currentPageStudents = studentList.subList(startIndex, endIndex); //会话request.getSession() // 将数据存储到request对象中,以便在JSP页面中使用 请求 request.setAttribute("currentPage", currentPage); request.setAttribute("totalPages", (int) Math.ceil((double) studentList.size() / pageSize)); request.setAttribute("studentList", currentPageStudents); // 转发到JSP页面 RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp"); dispatcher.forward(request, response); } private List getStudentList() { List studentList = new ArrayList<>(); try (Connection connection = JdcbConnection.requestConnection(); Statement statement = connection.createStatement()){ String sql = "select * from student"; ResultSet resultSet = statement.executeQuery(sql); while (resultSet.next()){ Student student = new Student( Integer.parseInt(resultSet.getString("id")), resultSet.getString("name"), resultSet.getString("age") ); studentList.add(student); } }catch (Exception e){ e.printStackTrace(); } // 此处可以连接数据库或其他数据源,这里只是模拟数据 return studentList; } }
JSP 代码
<%@ page import="java.util.List" %> <%@ page import="com.baidu.Student" %> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>分页显示学生列表 学生列表
ID | 姓名 | 年龄 |
---|---|---|
<%=studentList.get(i).getId() %> | <%=studentList.get(i).getName() %> | <%=studentList.get(i).getAge() %> |
${student.id} | --%> <%--${student.name} | --%> <%--${student.age} | --%> <%--
第<%=currentPage %> 页 / 共 <%=totalPages%> 页
<% int shang = currentPage-1;
if (shang ==0 ){
shang=1;
}
int xia = currentPage+1;
if (xia == totalPages+1 ){
xia = totalPages;
}
%>
上一页
下一页
<%-- 下一页--%>
<%--