前言:
阅读本文前,请先浏览分页功能分析文章,文章传送门SpringBoot案例-员工管理-分页查询-分析_熵240的博客-CSDN博客
根据三层架构中各个层次的作用进行编码
功能接口的实现
控制层(Controller类)
具体关键代码如下:
@GetMapping("/emps")
// 接收前端参数默认根据名称进行自动注入
public Result page(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer pageSize) {
// 设置未接受到参数值时,设置其默认值
// if (page == null) page = 1;
// if (pageSize == null) pageSize = 10;
log.info("分页查询,参数page:{}、pageSize:{}", page, pageSize);
// 调用Service中的方法进行分页查询
// 查询的结果封装到PageBean中
PageBean pageBean = empService.Page(page, pageSize);
return Result.success(pageBean);
}
业务层(Service类)
具体关键代码如下:
业务类
PageBean Page(Integer page, Integer pageSize);
业务实现类
public PageBean Page(Integer page, Integer pageSize) {
// 获取总记录数
long count = empMapper.CountAll();
Integer start = page * pageSize - pageSize;
// 获取分页查询结果列表
List<Emp> list = empMapper.GetData(start, pageSize);
// 封装PageBean对象
PageBean pageBean = new PageBean(count, list);
return pageBean;
}
持久层
具体关键代码如下:
/**
* 获取数据总数
*
* @return
*/
@Select("select count(*) from emp")
public long CountAll();
/**
* 获取每页数据信息
*
* @return
*/
@Select("select * from emp limit #{start},#{pageSize}")
public List<Emp> GetData(Integer start, Integer pageSize);
接口测试
在启动SpringBoot工程之后,在postman中进行接口测试,具体的请求路径及参数如下:
运行结果如下:
{
"code": 1,
"msg": "success",
"data": {
"total": 17,
"rows": [
{
"id": 1,
"username": "jinyong",
"password": "123456",
"name": "金庸",
"gender": 1,
"image": "1.jpg",
"job": 4,
"entrydate": "2000-01-01",
"deptId": 2,
"creteTime": null,
"updateTime": "2023-08-07T15:44:50"
},
{
"id": 2,
"username": "zhangwuji",
"password": "123456",
"name": "张无忌",
"gender": 1,
"image": "2.jpg",
"job": 2,
"entrydate": "2015-01-01",
"deptId": 2,
"creteTime": null,
"updateTime": "2023-08-07T15:44:50"
},
{
"id": 3,
"username": "yangxiao",
"password": "123456",
"name": "杨逍",
"gender": 1,
"image": "3.jpg",
"job": 2,
"entrydate": "2008-05-01",
"deptId": 2,
"creteTime": null,
"updateTime": "2023-08-07T15:44:50"
},
{
"id": 4,
"username": "weiyixiao",
"password": "123456",
"name": "韦一笑",
"gender": 1,
"image": "4.jpg",
"job": 2,
"entrydate": "2007-01-01",
"deptId": 2,
"creteTime": null,
"updateTime": "2023-08-07T15:44:50"
},
{
"id": 5,
"username": "changyuchun",
"password": "123456",
"name": "常遇春",
"gender": 1,
"image": "5.jpg",
"job": 2,
"entrydate": "2012-12-05",
"deptId": 2,
"creteTime": null,
"updateTime": "2023-08-07T15:44:50"
}
]
}
}
前后端联调测试
启动nginx项目,输入请求地址:http://localhost:90
运行结果如下:
前后端联调成功
小结
- 分页查询
- 请求参数:页码(page)、每页展示记录数(pageSize)
- 响应结果:总i记录数(total)、结果列表(PageBean)
- 注解
- @RequestParam(defaultValue=“1”)//设置请求参数的默认值