Implementación de la función de paginación JAVAWeb

Dirección de blog personal https://nfreak-man.cn
Al administrar cientos o miles de datos y mostrarlos en una lista, todos los datos se muestran en una página y la eficiencia es baja y la velocidad de carga será lenta. En este momento, los datos deben mostrarse en páginas.
Ejemplos:
list.jsp

La idea específica es escribir PageBean para obtener el número total de registros, el número de visualizaciones por página y el número de página actual, y obtener el número total de páginas por cálculo. Y obtenga los datos por página y guárdelos en la lista, cada vez que haga clic en la página siguiente para obtener los datos, cada vez que haga clic en la página anterior para mostrar los datos anteriores, de acuerdo con el número de página actual y el número de páginas por página, los datos de la lista se obtienen y se muestran varias veces. Y preste atención a los posibles errores en la página anterior de la página siguiente.

Escribe la clase PageBean

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 +
                '}';
    }
}

Escribir FindUserByPageServlet

Obtenga el número de página actual y el número de elementos que se muestran en cada página de la página, y llame al servicio para consultar

@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);
    }
}

Servicio de redacción de métodos

@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;
}

Escritura del método Dao

  1. Obtenga el número total de datos
  2. Según el índice obtenido para comenzar a buscar y el número de filas necesarias para encontrar la cantidad correspondiente de datos
@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);
}

Escritura de página frontal

<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>
Publicado 28 artículos originales · elogiado 0 · visitas 722

Supongo que te gusta

Origin blog.csdn.net/William_GJIN/article/details/104991857
Recomendado
Clasificación