springboot+thymeleaf实现分页

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013305783/article/details/82084118


   现在公司大多数都实现了前后端分离,前端使用Vue、React、AngularJS 等框架,不用完全依赖后端,但是如果对于比较小型的项目,没必要前后端分离,而Springboot与thymeleaf搭配是个不错的选择。

   在实际应用中,我们经常会对一些展示数据的页面进行分页,java后端分页使用PageHelper是个非常不错的选择,下面将会描述如何使用PageHelper+thymeleaf实现前端分页展示。
   首先引入相应的jar包

   <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper-spring-boot-starter</artifactId>
        <version>1.1.2</version>
        <type>pom</type>
    </dependency>
  <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
<dependency>
        <groupId>net.sourceforge.nekohtml</groupId>
        <artifactId>nekohtml</artifactId>
    </dependency>

   引入nekohtml使得程序能解析HTML文档并用标准的XML接口来访问其中的信息,否则在使用thymeleaf时可能会报一写语法上的错误。

   对于PageHelper只需要默认配置即可,如果有特殊需求可以自行在application.yml中配置
   接下来是后端实现分页:

 PageHelper.startPage(currentPage,1);
 List<MbBlogEntity> datas= searchDataDao.findIndexData();
 PageInfo<MbBlogEntity> pageInfo = new PageInfo<>(blogs);

   PageHelper.startPage(currentPage,1);第一个参数表示当前页面,第二个表示页长,下面一句紧邻需要分页的sql,分页信息可以用PageInfo来接收,然后将数据封装传递到前端,如果需要对分页信息进行处理可以自行封装。

public Map<String,Object> getMap(PageInfo<MbBlogEntity> pageInfo){
    Map<String,Object> map = new HashMap();
    Integer startPage = 0;
    Integer endPage = 0;
    map.put("pageNum",pageInfo.getPageNum());
    map.put("pageSize",pageInfo.getPageSize());
    map.put("size",pageInfo.getSize());
    map.put("startRow",pageInfo.getStartRow());
    map.put("endRow",pageInfo.getEndRow());
    map.put("total",pageInfo.getTotal());
    map.put("pages",pageInfo.getPages());
    map.put("prePage",pageInfo.getPrePage());
    map.put("nextPage",pageInfo.getNextPage());
    map.put("isFirstPage",pageInfo.isIsFirstPage());
    map.put("isLastPage",pageInfo.isIsLastPage());
    map.put("hasPreviousPage",pageInfo.isHasPreviousPage());
    map.put("hasNextPage",pageInfo.isHasNextPage());
    map.put("startPage",startPage);
    map.put("endPage",endPage);
    return map;
  }

   前端根据返回回来的分页数据进行相应的处理

  <a class="allpage"><b th:text="'共 '+ ${pages.pages}+ ' 页'"></b></a>
  <a th:if="${pages.hasPreviousPage} == true" th:href="@{'index?currentPage=' + ${pages.prePage}}"  >上一页</a>
  <a th:href="@{'index?currentPage=' + ${i}}"  th:each="i :${#numbers.sequence(pages.startPage, pages.endPage)}" th:text="${i}"  th:class="${pages.pageNum == i}? 'curPage' :'' "></a>

  &nbsp;&nbsp;<a th:href="@{'index?currentPage=' + ${pages.nextPage}}" th:if="${pages.hasNextPage} == true">下一页</a>
  &nbsp;&nbsp;<a th:href="@{'index?currentPage='+ ${pages.pages}}" >尾页</a>

   页面效果如下
这里写图片描述

猜你喜欢

转载自blog.csdn.net/u013305783/article/details/82084118