Java Web 普通分页显示代码

发布时间:2024年01月08日

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 {
        // 模拟从数据库或其他数据源获取学生列表
        List<Student> studentList = 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<Student> 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<Student> getStudentList() {
        List<Student> 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" %>
<html>
<head>
    <meta charset="UTF-8">
    <title>分页显示学生列表</title>
</head>
<body>

<h2>学生列表</h2>

<table border="1">
    <thead>
    <tr>
        <th>ID</th>
        <th>姓名</th>
        <th>年龄</th>
    </tr>
    </thead>
    <tbody>
    <%
        int currentPage = (int) request.getAttribute("currentPage");
        int totalPages = (int) request.getAttribute("totalPages");
        List<Student> studentList = (List) request.getAttribute("studentList");
    %>
    <%
        for (int i = 0; i < studentList.size(); i++) {
    %>
    <tr>
        <td><%=studentList.get(i).getId() %></td>
        <td><%=studentList.get(i).getName() %></td>
        <td><%=studentList.get(i).getAge() %></td>
    </tr>
    <%
        }
    %>
<%--    <c:forEach var="student" items="${studentList}">--%>

<%--        <tr>--%>
<%--            <td>${student.id}</td>--%>
<%--            <td>${student.name}</td>--%>
<%--            <td>${student.age}</td>--%>
<%--        </tr>--%>
<%--    </c:forEach>--%>
    </tbody>
</table>

<p>
    第<%=currentPage %> 页 / 共 <%=totalPages%> 页

<% int shang = currentPage-1;
   if (shang ==0 ){
       shang=1;
   }
   int xia = currentPage+1;
   if (xia == totalPages+1 ){
       xia = totalPages;
   }
%>
    <a href="/StudentServlet?page=<%=shang%>">上一页</a>
    <a href="/StudentServlet?page=<%=xia%>">下一页</a>
<%--    <a href="?page=${currentPage + 1}">下一页</a>--%>
<%--    <c:if test="${currentPage > 1}">--%>
<%--        <a href="?page=${currentPage - 1}">上一页</a>--%>
<%--    </c:if>--%>
<%--    <c:if test="${currentPage < totalPages}">--%>
<%--        --%>
<%--    </c:if>--%>
</p>

</body>
</html>
</body>

</html>

数据库连接

package com.baidu;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JdcbConnection {
    public static Connection requestConnection() throws ClassNotFoundException, SQLException {
        //注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //获取连接
        String url = "jdbc:mysql://127.0.0.1:3306/db2";
        String username = "root";
        String password = "Lin58936543@";
        return DriverManager.getConnection(url,username,password);

    }

}

封装实体类

package com.baidu;

public class Student {
    private int id ;
    private String name;
    private String age;

    public Student() {
    }

    public Student(int id, String name, String age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age='" + age + '\'' +
                '}';
    }
}
文章来源:https://blog.csdn.net/m0_65037354/article/details/135449345
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。