返回的Json格式如下:
{
"success": true,
"errorCode": null,
"errorMessage": null,
"data": {
"rows": [
{
"id": 1,
"name": "小明",
"age": 12,
"sex": 1,
"hobby": "打游戏",
"mobile": "123456789000",
"address": "南京"
},
{
"id": 2,
"name": "小华",
"age": 11,
"sex": 2,
"hobby": "看动漫",
"mobile": "123456789000",
"address": "南京"
},
//省略
......
],
"page": 1, //当前页
"total": 2, //总页数
"records": 11, //总条数
"code": null, //返回状态码
"message": null,//返回信息
"size": 10 //页大小
}
}
com.github.pagehelper
pagehelper-spring-boot-starter
1.2.3
@PostMapping("/list")
@ResponseBody
public PageBaseInfo findStudentList(@RequestBody Student student,
@RequestParam(required = false, defaultValue = "1") int page,
@RequestParam(required = false, defaultValue = "10") int rows){
try {
/*
* 分页设置
* page:当前页码 rows:显示条数
*/
PageHelper.startPage(page, rows);
List list = studentService.list(student);
PageInfo pageInfo = new PageInfo<>(list);
// 总条数
int totalRow = (int) pageInfo.getTotal();
logger.info("StudentController invoke method findStudentList is SUCCESS!! result ==> {} " + JSON.toJSONString(list));
return new BaseResult<>(new PageBaseInfo(list,page,totalRow,rows));
} catch (Exception e) {
logger.error("StudentController invoke method findStudentList failed! cause : " + e);
return new BaseResult<>(ParamReturnEnum.ERROR_MSG_SYSTEM_ERROR.getCode(), ParamReturnEnum.ERROR_MSG_SYSTEM_ERROR.getMessage());
}
}
这里的关键是要获取记录的总条数,而非当前页显示的总条数,那个是页大小。
然后将查询到的数据和前端传来的分页数据传给PageBaseInfo,这样就返回了分页后的具体信息。
后面业务层和持久层代码就不贴了,就正常也调用逻辑就可以了,MyBatis也是正常查询语句。
下面贴出返回到前端的封装基类代码。
public class PageBaseInfo {
//需要显示的数据集 每页显示的数据量
@SuppressWarnings("rawtypes")
private List rows;
//当前页
private long page;
//总页数
private long total;
//总记录数
private long records;
//反馈状态码
private String code;
//反馈信息
private String message;
private long size;
//默认页面容量为20
public final static long NO_SIZE = 20;
public PageBaseInfo() {
this.size= NO_SIZE;
}
public PageBaseInfo(List rows, long page, long records, long size) {
this.rows = rows;//数据集合
this.page = page;//当前页
this.records = records;//总记录数
this.size = size;//页面容量
this.total = (records + this.size - 1)/this.size;//总页数
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
@SuppressWarnings("rawtypes")
public List getRows() {
return rows;
}
@SuppressWarnings("rawtypes")
public void setRows(List rows) {
this.rows = rows;
}
public long getPage() {
return page;
}
public void setPage(long page) {
this.page = page;
}
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
public long getRecords() {
return records;
}
public void setRecords(long records) {
this.records = records;
//设置总记录数的时候同时设置总页数
setTotal((records + this.size - 1)/this.size);
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}