Implementation of JAVAWeb paging function

Personal blog address https://nfreak-man.cn
When managing hundreds or thousands of data and displaying them in a list, all the data is displayed on one page and the efficiency is low and the loading speed will be slow. At this time, the data needs to be displayed in pages.
Examples:
list.jsp

The specific idea is to write PageBean to obtain the total number of records, the number of displays per page and the current page number, and obtain the total number of pages by calculation. And get the data by page and save it in the list, every time you click the next page to get the data, every time you click the previous page to display the previous data, according to the current page number and the number of pages displayed, the list data is obtained and displayed multiple times. And pay attention to the possible bugs in the previous page of the next page.

Write the PageBean class

public class PageBean<T> {
    private int totalCount;//总记录数
    private int totalPage;//总页码
    private List<T> list;//每页的数据
    private int currentPage;//当前页码
    private int rows;//每页显示记录数

    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }

    public int getTotalPage() {
        return totalPage;
    }

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

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

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

    public int getCurrentPage() {
        return currentPage;
    }

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

    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    @Override
    public String toString() {
        return "PageBean{" +
                "totalCount=" + totalCount +
                ", totalPage=" + totalPage +
                ", list=" + list +
                ", currentPage=" + currentPage +
                ", rows=" + rows +
                '}';
    }
}

Write FindUserByPageServlet

Get the current page number and the number of items displayed on each page from the page, and call service to query

@WebServlet("/findUserByPageServlet")
public class FindUserByPageServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取参数
        String currentPage = request.getParameter("currentPage");//当前页码
        String rows = request.getParameter("rows");//每页显示条数
        if(currentPage == null || "".equals(currentPage)){//防止空页面或参数丢失报错
            currentPage = "1";
        }
        if(rows == null || "".equals(rows)){
            rows = "5";
        }
        //调用service查询
        UserSvice service = new UserServiceImpl();
        PageBean<User> pb = service.finUserByPage(currentPage,rows);
        //将PageBean存入request
        request.setAttribute("pb",pb);
        //转发到list.jsp
        request.getRequestDispatcher("/list.jsp").forward(request,response);
    }

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

Service method writing

@Override
public PageBean<User> finUserByPage(String _currentPage, String _rows) {
    int currentPage = Integer.parseInt(_currentPage);
    int rows = Integer.parseInt(_rows);
    if(currentPage <= 0){//防止用户在第一页时点击前一页报错
        currentPage = 1;
    }
    //创建空的PageBean对象
    PageBean<User> pb = new PageBean<User>();
    //设置参数
    pb.setCurrentPage(currentPage);
    pb.setRows(rows);
    //调用dao查询总记录数
    int totalCount = dao.findTotalCount();
    pb.setTotalCount(totalCount);
    //调用dao查询list集合
    //计算开始的记录的索引
    int start = (currentPage - 1) * rows;
    List<User> list = dao.findByPage(start,rows);
    pb.setList(list);
    //计算总页码
    int totalPage = totalCount % rows == 0 ? totalCount/rows : totalCount/rows + 1;
    pb.setTotalPage(totalPage);
    return pb;
}

Dao method writing

  1. Get the total number of data
  2. According to the obtained index to start searching and the number of rows needed to find the corresponding amount of data
@Override
public int findTotalCount() {
    String sql = "select count(*) from user";
    return template.queryForObject(sql,Integer.class);
}

@Override
public List<User> findByPage(int start, int rows) {
    String sql = "select * from user limit ? , ?";
    return template.query(sql,new BeanPropertyRowMapper<User>(User.class),start,rows);
}

Front-end page writing

<form id="form1" action="${pageContext.request.contextPath}/delSelectedServlet" method="post">
<table border="1" class="table table-bordered table-hover">
    <tr class="success">
        <th><input type="checkbox" id="firstCb"></th>
        <th>编号</th>
        <th>姓名</th>
        <th>性别</th>
        <th>年龄</th>
        <th>籍贯</th>
        <th>QQ</th>
        <th>邮箱</th>
        <th>操作</th>
    </tr>
    <c:forEach items="${pb.list}" var="user" varStatus="s">//将PageBean获取的list展示到页面
        <tr>
            <th><input type="checkbox" name="uid" value="${user.id}"></th>
            <td>${s.count}</td>
            <td>${user.name}</td>
            <td>${user.gender}</td>
            <td>${user.age}</td>
            <td>${user.address}</td>
            <td>${user.qq}</td>
            <td>${user.email}</td>
            <td><a class="btn btn-default btn-sm" href="${pageContext.request.contextPath}/findUserServlet?id=${user.id}">修改</a>&nbsp;
                <a class="btn btn-default btn-sm" href="javascript:deleteUser(${user.id});">删除</a></td>
        </tr>
    </c:forEach>
</table>
</form>
<div>//分页组件
    <nav aria-label="Page navigation">
        <ul class="pagination">
            <c:if test="${pb.currentPage == 1}"><li class="disabled"></c:if>
            <c:if test="${pb.currentPage != 1}"><li></c:if>
                <a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pb.currentPage - 1}&rows=5" aria-label="Previous">
                    <span aria-hidden="true">&laquo;</span>
                </a>
            </li>
            <c:forEach begin="1" end="${pb.totalPage}" var="i">
                <c:if test="${pb.currentPage == i}">
                    <li class="active"><a 		                         href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${i}&rows=5">${i}</a></li>
                </c:if>
                <c:if test="${pb.currentPage != i}">
                    <li><a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${i}&rows=5">${i}</a></li>
                </c:if>
            </c:forEach>
               //下一页按钮禁用状态及报错处理
                <c:if test="${pb.currentPage == pb.totalPage}"><li class="disabled"><a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pb.currentPage}&rows=5" aria-label="Next">
                    <span aria-hidden="true">&raquo;</span>
                </a>
                </li></c:if>
                <c:if test="${pb.currentPage < pb.totalPage}"><li><a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pb.currentPage + 1}&rows=5" aria-label="Next">
                        <span aria-hidden="true">&raquo;</span>
                    </a>
                </li>
                </c:if>

            <span style="font-size: 25px;margin-left: 5px">
                共${pb.totalCount}条记录,共${pb.totalPage}页
            </span>
        </ul>
    </nav>
</div>
Published 28 original articles · praised 0 · visits 722

Guess you like

Origin blog.csdn.net/William_GJIN/article/details/104991857