添加依赖

  • 这里展示了两个Pagehelper的依赖,这里是springboot项目,所以就用第二个依赖,避免后面使用产生一些bug;
1
2
3
4
5
6
7
8
9
10
11
12
13
    <!--分页插件1-->
<!-- <dependency>-->
<!-- <groupId>com.github.pagehelper</groupId>-->
<!-- <artifactId>pagehelper</artifactId>-->
<!-- <version>5.2.1</version>-->
<!-- </dependency>-->

<!--分页插件2-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>

在application.yaml或者application.properties配置文件中配置(看你用的是哪一个)

  • application.yaml文件的配置
1
2
3
4
5
6
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params:
count: countSql
  • application.properties文件的配置
1
2
3
4
5
#分页插件配置
pagehelper.helper-dialect=mysql
pagehelper.reasonable=true
pagehelper.support-methods-arguments=true
pagehelper.params=count=countSql

controller层

1
2
3
4
5
6
7
8
9
10
11
@GetMapping("/userlist")
public String userlist(@RequestParam(value = "page", defaultValue = "1") Integer page, Model model){
//获取指定页数据,每页显示10条数据
PageHelper.startPage(page,10);
//紧跟的第一个select方法被分页
List<Student> students = studentService.selectAll();
//使用PageInfo包装数据 navigatePages表示导航标签的数量
PageInfo pageInfo = new PageInfo(students,3);
model.addAttribute("pageInfo",pageInfo);
return "admin/user/user-list";
}

controller层

设置html页面分页

  • 记得在HTML标签引用thymeleaf:

    1
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<div class="layui-card-body ">
<div class="page">
<!--分页-->
<div class="Pages" align="center">
<span>
<a th:href="@{|userlist?page=1|}">首页</a>
</span>
<span th:if="${pageInfo.hasPreviousPage==true}">
<a th:href="@{|userlist?page=${pageInfo.pageNum-1}|}">上一页</a>
</span>
<span th:each="page:${pageInfo.navigatepageNums}">
<a th:href="@{|userlist?page=${page}|}" th:text="${page}"></a>
</span>
<span th:if="${pageInfo.hasNextPage==true}">
<a th:href="@{|userlist?page=${pageInfo.pageNum+1}|}">下一页</a>
</span>
<span>
<a th:href="@{|userlist?page=${pageInfo.pages}|}">末页</a>
</span>
当前页:第<span th:text="${pageInfo.pageNum}"></span>/<span th:text="${pageInfo.pages}"></span>
</div>
</div>
</div>
  • 效果图:

效果图

  • PageHelper中默认PageInfo成员变量
1
2
3
4
5
6
7
8
9
10
11
12
<!--PageHelper中默认PageInfo成员变量-->
<div>当前页号:<span th:text="${pageInfo.pageNum}"></span></div>
<div>每页条数:<span th:text="${pageInfo.pageSize}"></span></div>
<div>起始行号:<span th:text="${pageInfo.startRow}"></span></div>
<div>终止行号:<span th:text="${pageInfo.endRow}"></span></div>
<div>总结果数:<span th:text="${pageInfo.total}"></span></div>
<div>总页数:<span th:text="${pageInfo.pages}"></span></div>
<hr/>
<div>是否为第一页:<span th:text="${pageInfo.isFirstPage}"></span></div>
<div>是否为最后一页:<span th:text="${pageInfo.isLastPage}"></span></div>
<div>是否有前一页:<span th:text="${pageInfo.hasPreviousPage}"></span></div>
<div>是否有下一页:<span th:text="${pageInfo.hasNextPage}"></span></div>