乐趣区

关于技术:thymeleaf-实现分页功能

分页查问是一个很常见的性能, 对于分页也有很多封装好的轮子供咱们应用。

本文通过应用 SpringBoot+Mybatis-plus 实现前端后端的分页性能, 并没有应用插件来实现, 前端次要是应用 Thymeleaf 来渲染分页的页码信息。

前段页面分页代码

<nav class="mt-5" th:if="${pageInfo.totalPage>0}" th:fragment="pagination">
    <!-- align-items-center -->
    <ul class="pagination justify-content-center">
      <li th:class="|page-item ${pageInfo.pageNum==1?'disabled':''}|">
        <a class="page-link"
           th:href="@{${pageInfo.path}(pageNum=${pageInfo.pageNum}-1)}">&laquo; Previous</a>
      </li>
      <li th:class="|page-item ${i==pageInfo.pageNum?'active':''}|"th:each="i:${#numbers.sequence(pageInfo.getFrom(),pageInfo.getTo())}">
        <a class="page-link" th:href="@{${pageInfo.path}(pageNum=${i})}" th:text="${i}">1</a></li>
      <li th:class="|page-item ${pageInfo.pageNum>=pageInfo.totalPage?'disabled':''}|">
        <a class="page-link" th:href="@{${pageInfo.path}(pageNum=${pageInfo.pageNum+1})}">Next &raquo;</a>
      </li>
    </ul>
</nav>
  • pageInfo.pageNum 依据本人的逻辑定义
  • pageInfo.path 不便将整个分页片段援用到其余页面, 如果不须要被援用, 间接写死门路也能够

管制层 Controller

  @RequestMapping("discuss/{userId}")
  public ModelAndView getIndexPage(
      PageInfo pageInfo,
      @RequestParam(name = "orderMode", defaultValue = "0") int orderMode) {
    ...
    ModelAndView mav = new ModelAndView();
    pageInfo = new PageInfo();
    page.setPath("user/discuss/" + userId);
    pageInfo.setPageNum(pageNum);
    // 这里把文章分类带到页面 header 实现动静加载分类
    IPage<Post> postIPage = postService.postPage(orderMode, pageNum);
    pageInfo.setTotal(postIPage.getTotal());
    pageInfo.setTotalPage(ObjUtils.toInteger(postIPage.getPages()));
    List<Post> records = postIPage.getRecords();
    pageInfo.setRows(records);
    List<Map<String, Object>> discussPosts = new ArrayList<>();
    ...

    mav.addObject("pageInfo", pageInfo);
    mav.addObject("orderMode", orderMode);
    mav.addObject("discussPosts", discussPosts);
    mav.setViewName("site/my-post");
    return mav;
  }

page.setPath(“user/discuss/” + userId); 门路最前边必须退出‘/’, 如果仅是 user/discuss/, 点击分页的时候会多出一层

https://localhost/user/discuss/user/discuss/2?pageNum=2

服务层 service

public IPage<Post> postPage(Integer orderMode, Integer currentPage) {QueryWrapper<Post> wrapper = new QueryWrapper<>();
    if (orderMode != 0) {wrapper.eq("a", orderMode);
    }
    wrapper.orderByDesc("score", "created");
    // 第 1 页,每页 2 条
    Page<Post> page = new Page<>(currentPage, POSTSIZE);
    IPage<Post> postIPage = postMapper.selectPage(page, wrapper);
    // 获取以后数据
    return postIPage;
  }

数据拜访层 mapper

@Repository
public interface PostMapper extends BaseMapper<Post> {}

获取 pageInfo 工具类

关注我获取更多干货

退出移动版