WEB应用技术第十次作业-分页PageHelper

📅 2026/7/7 15:40:25
WEB应用技术第十次作业-分页PageHelper
一、整体思路前端传递两个参数page当前页码、pageSize每页数据条数Service 层手动计算分页起始下标start (page -1)*pageSizeMapper 写两条 SQL一条统计符合条件数据总条数select count(*) from 表一条使用 limit 截取当前页数据select * from 表 limit start,pageSize自定义PageBean实体封装总条数 total、当前页数据 rows统一返回前端二、实现代码1.新建分页封装类 PageBeanpackage com.example.myweb.pojo; import lombok.Data; import java.util.List; Data public class PageBean { private Long total; //总商品条数 private ListGoods rows; //当前页商品数据 }2.GoodsMapper新增两条分页 SQL//1. 多条件统计商品总数量 Select(scriptSELECT count(*) FROM goods where if testname ! \\name LIKE CONCAT(%,#{name},%)/if if testcategory ! \\category#{category}/if/where/script) Long countByCondition(Param(name)String name,Param(category)String category); //2. limit分页查询商品 Select(scriptSELECT * FROM goods where if testname ! \\name LIKE CONCAT(%,#{name},%)/if if testcategory ! \\category#{category}/if/where ORDER BY create_time DESC limit #{start},#{pageSize}/script) ListGoods selectPageData(Param(start)Integer start, Param(pageSize)Integer pageSize, Param(name)String name, Param(category)String category);3.GoodsServiceImpl 分页业务Override public PageBean goodsPage(Integer page,Integer pageSize,String name,String category){ //页码容错 int safePage pagenull||page1 ? 1 : page; int safeSize pageSizenull||pageSize1 ? 10 : pageSize; //计算起始偏移量 int start (safePage-1)*safeSize; //查询总条数 Long total goodsMapper.countByCondition(name,category); //分页截取数据 ListGoods list goodsMapper.selectPageData(start,safeSize,name,category); return new PageBean(total,list); }4.GoodsController 接口GetMapping public ResultPageBean goodsPage( RequestParam(defaultValue 1) Integer page, RequestParam(defaultValue 10) Integer pageSize, RequestParam(required false) String name, RequestParam(required false) String category ){ PageBean pageBean goodsService.goodsPage(page,pageSize,name,category); return Result.success(pageBean); }5.前端取值axios.get(http://localhost:8080/goods?params).then(res{ if(res.data.code 1){ this.goodsList res.data.data.rows; this.totalCount res.data.data.total; } })