PageHelper 是一个 MyBatis 的分页插件,支持多种数据库,可查看官网,负责将已经写好的 SQL 语句,进行SQL分页加工。无需你自己去封装以及关心 SQL 分页等问题,支持多种分页方式,如从第0或第一页开始, 使用很方便。
添加依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
配置分页插件
修改 application.properties,如下配置:
pagehelper.reasonable=true
# 合理化分页,查询当前页小于1时会查第一页,大于总页数时查最后一页
pagehelper.page-size-zero=true
# 当每页大小为零,或limit = 0时会查询全部内容,但结果依旧为PageInfo类型
使用 PageHelper 分页插件
- 删除 Mapper.xml 文件中查询总数量的代码。
- 删除 Mapper.xml 文件的分页查询SQL 中的 Limit 子句,QueryObject 中也不需要提供 getStart 方法了。
- 使用分页插件提供的 PageInfo 类进行封装,不需要我们自己再定义 PageResult 类了。
//业务实现类
public PageInfo<Department> query(QueryObject qo) {
// 使用分页插件,传入当前页,每页显示数量
PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
//查询出来全部数据
List<Department> departments = departmentMapper.selectForList(qo);
return new PageInfo(departments);
}
其底层就是根据拦截到之前那条查询全部的sql,然后去那张表先查询总数据条数,最后给我们的这条查询全部数据的sql拼接limit子句再将查询出来的数据封装到PageInfo类型对象中
前端 twbs-pagination 分页插件
twbs-pagination 是一个简单的自适应 Bootstrap 样式的分页插件,用于前端绘制分页相关的样式效果。官网https://esimakin.github.io/twbs-pagination/
在官网下载插件并放入项目中,在需要使用的模板文件中引入 jq 和bootstrap 和这个插件的js
<ul id="pagination-demo" class="pagination-sm"></ul>
//需要定义一个拥有这样id和class的ul标签
$(function(){
var totalPages = /*[[${pageInfo.pages}]]*/ 1;
var startPage = /*[[${pageInfo.pageNum}]]*/ 1;
//这个插件给jq对象添加一个方法twbsPagination
$('#pagination').twbsPagination({
totalPages: totalPages, //总页数
startPage: startPage,//当前页
first:'首页',
prev:'上一页',
next:'下一页',
last:'尾页',
visiblePages: 5,//可见页数
onPageClick: function (event, page) {
$('#currentPage').val(page);//将点击的页码传入我们的表单
$('#searchForm').submit();//找到表单并提交查询请求,会带上这个页码
}
});
});
SweetAlert2
SweetAlert2 是一个美观,响应,可定制,替代 JavaScript 的弹出框。
引入插件
<link rel="stylesheet" href="/static/js/plugins/sweetalert2/sweetalert2.min.css">
<script src="/static/js/plugins/sweetalert2/sweetalert2.min.js"></script>
使用插件
在为一个按钮绑定点击事件,响应函数加上下面代码
Swal.fire({
title: '标题',
text: "内容",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: '确定',
cancelButtonText: '取消'
}).then((result) => {
if(result.value) {
// 点了确定做什么,由开发者决定
}
});