【JavaWeb】手写一个Servlet+JSP+JavaBean分页

在这里插入图片描述

✅✅作者主页:🔗孙不坚1208的博客
🔥🔥精选专栏:🔗JavaWeb从入门到精通(持续更新中)
📋📋 本文摘要:本篇文章主要分享如何使用Servlet+JSP+JavaBean写一个分页。

💞💞觉得文章还不错的话欢迎大家点赞👍➕收藏⭐️➕评论💬支持博主🤞
👉 👉你的一键三连是我更新的最大动力❤️❤️

运行环境:tomcat8.0+idea

技术:servlet+jsp+javabean+mysql

一、分页技术

1、前端分页

前端分页:一次性从数据库读出表的所有数据一次性的返回给客户端,由前端js来控制每一页的显示,由于一次性读出所有数据并返回给客户端,如果数据量庞大,这一次的动作可能是非常消耗服务器资源和带宽的,但是返回给客户端以后就非常轻松了,客户端在一段时间内不会再像服务器端请求资源。

2、后端分页

本文分页是后端分页实现的一种。

后端分页:由后端程序控制,每一次只返回一页大小的数据,返回并显示到客户端,优点的话就是减少单次查询数据库的时间,后端分页的方法需要频繁和服务器端进行交互,因为频繁交互,所以会给服务器带来负担。

二、实现分页

1、准备工作

在制作分页之前,首先需要了解,分页的属性有哪些?

  • 当前页数 currentPage
  • 总页数 totalPage
  • 总记录数 totalSize
  • 每页记录数 pageSize
  • 当前页数据 pageList
  • 等等…

我们可以将这些属性变成一个JavaBean中的属性来调用,并且实现一些分页相关的业务逻辑。

封装关于页数的数据:

请求数据: 当前页数 currentPage

响应数据: PageBean 类封装(包含上面我们说过的属性)

总页数 = (总记录数 % 每页记录数 == 0) ? (总记录数 / 每页记录数) : (总记录数 / 每页记录数 + 1);

当前页数据 list = query( select * from limit 每页记录数*(当前页数-1), 每页记录数 );

2、效果图

image-20221118182545962

3、核心代码

bean PageBean.java

package com.sun.bean;

import com.sun.util.DBConnection;
import com.sun.util.Date_String;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author JumperSun
 * @date 2022-11-15-8:31
 */
public class PageBean<T> {
    private Integer currentPage; // 当前页数
    private Integer totalPage; // 总页数
    private Integer totalSize; // 总记录数
    private Integer pageSize; // 每页记录数
    private List<T> list; // 当前页数据 <T>

    public Integer getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(Integer currentPage) {
        this.currentPage = currentPage;
    }

    public Integer getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(Integer totalPage) {
        this.totalPage = totalPage;
    }

    public Integer getTotalSize() {
        return totalSize;
    }

    public void setTotalSize(Integer totalSize) {
        this.totalSize = totalSize;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }

    // 分页总数
    public int size()throws SQLException {
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        try {
            conn = DBConnection.getConnection();
            String sql = "select count(*) from user";
            st = conn.createStatement();
            rs = st.executeQuery(sql);
            if(rs.next()) {
                return rs.getInt(1);
            }
        } finally {
            DBConnection.close(rs, st, conn);
        }
        return 0;
    }

    // 分页查询数据
    public List<UserBean> queryAllByLimit(int offset, int limit) throws SQLException {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<UserBean> users=new ArrayList<UserBean>();
        try {
            conn = DBConnection.getConnection();
            String sql = "select * from user limit " + offset + "," + limit;
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while(rs.next()==true){
                UserBean tmp=new UserBean();
                tmp.setUserid(rs.getInt("id"));
                tmp.setUsername(rs.getString("name"));
                tmp.setPassword(rs.getString("password"));
                tmp.setSex(rs.getString("sex"));
                tmp.setAge(rs.getInt("age"));
                String birthday= Date_String.getStringDate1(rs.getDate("birthday"));
                tmp.setBirthday(birthday);
                users.add(tmp);
            }
        } finally {
            DBConnection.close(rs, ps, conn);
        }
        return users;
    }

    // 分页查询处理
    public void selectUserListByPage(Integer currentPage, PageBean<UserBean> pageBean) throws SQLException {
        // 当前页数
        pageBean.setCurrentPage(currentPage);
        // 总记录数
        Integer totalSize = pageBean.size();
        pageBean.setTotalSize(totalSize);
        // 每页记录数
        Integer pageSize = 3;
        pageBean.setPageSize(pageSize);
        // 总页数(没余数为整页,有余数页数+1)
        Integer totalPages = null;
        if (totalSize != null) {
            totalPages = (totalSize%pageSize==0) ? (totalSize/pageSize) : (totalSize/pageSize+1);
        }
        if(totalPages != null) {
            pageBean.setTotalPage(totalPages);
        }
        // 当前页数据
        List<UserBean> list = queryAllByLimit(pageSize*(currentPage-1), pageSize);
        pageBean.setList(list);
    }
}

Servlet GetUserListByPage.java

package com.sun.servlet;

import java.io.IOException;
import java.sql.SQLException;

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 com.sun.bean.PageBean;
import com.sun.bean.UserBean;

@WebServlet("/getUserListByPage")
public class GetUserListByPage extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String currentPageStr = request.getParameter("currentPage");
		Integer currentPageNum = getCurrentPage(currentPageStr);

		PageBean<UserBean> pageBean = new PageBean<>();
		try {
			pageBean.selectUserListByPage(currentPageNum,pageBean);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		request.setAttribute("pageBean", pageBean);
		request.getRequestDispatcher("/Main.jsp").forward(request,response);
	}

	private Integer getCurrentPage(String currentPagestr) {
		if (null == currentPagestr) {
			currentPagestr = "1";
		}
		return Integer.valueOf(currentPagestr);
	}

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

}

jsp Main.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" errorPage="../error.jsp" %>
<%@ page import="java.util.List" %>
<%@ page import="com.sun.bean.UserBean" %>
<%@ page import="com.sun.bean.PageBean" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <link rel="stylesheet" type="text/css" href="<%=request.getContextPath() %>/css/style.css"/>
    <link rel="stylesheet" type="text/css" href="<%=request.getContextPath() %>/css/common.css"/>
</head>
<body>
<div class="content">
    <jsp:useBean id="pageBean" class="com.sun.bean.PageBean" scope="request"/>
    <table class="mtable2">
        <h3 style="margin-bottom: 0">学生列表</h3>
        <form action="${pageContext.request.contextPath}/getUserListByPageLike" method="post">
            学生名:<input type="text" name="username" value="${param.username}"/>&nbsp;&nbsp;
            性别:<input type="text" name="sex" value="${param.sex}"/>
            <input type="submit" value="查询"/>
            <input type="reset" value="重置">
        </form>
        <tr>
            <th>学生id</th>
            <th>学生名</th>
            <th>密码</th>
            <th>性别</th>
            <th>年龄</th>
            <th>出生日期</th>
            <th>操作</th>
        </tr>
        <c:forEach items="${pageBean.list}" var="user">
            <tr>
                <td>${user.getUserid()}</td>
                <td>${user.getUsername()}</td>
                <td>${user.getPassword()}
                </td>
                <td>${user.getSex()}
                </td>
                <td>${user.getAge()}
                </td>
                <td>${user.getBirthday()}
                </td>
                <td>
                    <a href="user/UpdateUser.jsp?userid=${user.getUserid()}">修改</a>&nbsp;&nbsp;&nbsp;&nbsp;
                    <a href="user/DelUser_do.jsp?userid=${user.getUserid()}">删除</a>
                </td>
            </tr>
        </c:forEach>
    </table>
    <div class="fenye">
        第${pageBean.currentPage}/${pageBean.totalPage}页
        总记录数:${pageBean.totalSize}条
        每页${pageBean.pageSize}条
        <c:if test="${pageBean.currentPage != 1}">
            <a href="${pageContext.request.contextPath}/getUserListByPageLike?currentPage=1">
                [首页]
            </a>
            <a href="${pageContext.request.contextPath}/getUserListByPageLike?currentPage=${pageBean.currentPage-1}">
                [上一页]
            </a>
        </c:if>
        <c:if test="${pageBean.currentPage != pageBean.totalPage}">
            <a href="${pageContext.request.contextPath}/getUserListByPageLike?currentPage=${pageBean.currentPage+1}">
                [下一页]
            </a>
            <a href="${pageContext.request.contextPath}/getUserListByPageLike?currentPage=${pageBean.totalPage}">
                [尾页]
            </a>
        </c:if>
    </div>
</div>
</body>
</html>

此致,一个分页就写完了。

  • 74
    点赞
  • 86
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 53
    评论
分页是常见的网页数据展示功能,在JavaWeb开发中,可以使用ServletJSP实现分页功能。 ServletJavaWeb开发中服务端的组件,可以接收客户端的请求并处理相关业务逻辑。在分页功能的实现中,需要通过Servlet来获取数据库中的数据,并将数据传递给JSP进行展示。 在Servlet中,可以通过获取请求中的参数来确定当前页数和每页显示的数据条数。根据这些参数,可以计算出需要查询的数据起始位置。 代码示例: ```java @WebServlet("/page") public class PageServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int currentPage = Integer.parseInt(request.getParameter("currentPage")); int pageSize = Integer.parseInt(request.getParameter("pageSize")); // 计算起始位置 int start = (currentPage - 1) * pageSize; // 从数据库中查询数据 List<Data> dataList = getDataFromDB(start, pageSize); // 将数据存入request中 request.setAttribute("dataList", dataList); // 将请求转发给JSP进行展示 request.getRequestDispatcher("/page.jsp").forward(request, response); } private List<Data> getDataFromDB(int start, int pageSize) { // 从数据库中查询数据,并返回查询结果 // ... } } ``` 在JSP中,可以通过EL表达式获取Servlet中存入request的数据,并通过循环和条件判断来展示数据。 代码示例: ```jsp <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>分页展示</title> </head> <body> <table> <tr> <th>ID</th> <th>姓名</th> <th>年龄</th> </tr> <c:forEach items="${dataList}" var="data"> <tr> <td>${data.id}</td> <td>${data.name}</td> <td>${data.age}</td> </tr> </c:forEach> </table> </body> </html> ``` 以上代码示例展示了使用ServletJSP实现分页功能的基本思路和示例代码。实际开发中,还需要根据具体需求进行相关配置和逻辑的完善。
评论 53
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

請你喝杯Java

感谢您的支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值