# SpringBoot + MybatisPlus + javascript 分页功能

# 导入依赖

SpringBoot3.2.2 版本使用如下的 MybatisPlus 依赖否则报错,因为不兼容版本

<dependency>
   <groupId>com.baomidou</groupId>
   <artifactId>mybatis-plus-spring-boot3-starter</artifactId>
   <version>3.5.5</version>
</dependency>

导入了 MybatisPlus 就可以编写工具类代码了,如下:

配置 MybatisPlus 分页的配置类

可以写到 com.dkx.config 包中

/**
 * <P>
 * 		Mybatis-Plus 配置
 * </p>
 */
@Configuration
@MapperScan("com.dkx.mapper")
public class MybatisPlusConfig {
	/**
	 * 新的分页插件
	 * 需要设置 MybatisConfiguration#useDeprecatedExecutor = false
	 * 避免缓存出现问题 (该属性会在旧插件移除后一同移除)
	 */
	@Bean
	public MybatisPlusInterceptor mybatisPlusInterceptor() {
		MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
		interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
		return interceptor;
	}
}

这个类可以放到 com.dkx.util 包中,然后分页会用

分页参数类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class PageParams {
    // 当前页码
    private long pageNo;
    // 每页显示记录数
    private long pageSize = Integer.MAX_VALUE;
}

返回分页的数据类

@Data
@ToString
public class PageResult<T> implements Serializable {
    // 数据列表
    private List<T> items;
    // 总记录数
    private long counts;
    // 当前页码
    private long page;
    // 每页记录数
    private long pageSize;
    public PageResult(List<T> items, long counts, long page, long pageSize) {
        this.items = items;
        this.counts = counts;
        this.page = page;
        this.pageSize = pageSize;
    }
}

响应类

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result<T> {
    private int code;
    private String message;
    private T data;
    public Result(T data) {
        this.code = 200;
        this.message = "success";
        this.data = data;
    }
    public Result(T data, boolean success, String message) {
        if (success) {
            this.code = 200;
            this.message = "success";
        } else {
            this.code = 500;
            this.message = message;
        }
        this.data = data;
    }
    public Result(int code, String message) {
        this.code = code;
        this.message = message;
        this.data = null;
    }
    public static <T> Result<T> success(T data) {
        return new Result<>(data);
    }
    public static <T> Result<T> fail(String message) {
        return new Result<>(500, message);
    }
    public static <T> Result<T> fail(int code, String message) {
        return new Result<>(code, message);
    }
}

image-2024021210933410

以上都可以放到 util 中管理

PS:不用写 Mapper 类的代码

service 类

PageResult<实体类> getAll(PageParams pageParams, @RequestBody(required = false) 实体类 xxx);
  • 演示如下:
PageResult<Book> getAll(PageParams pageParams, @RequestBody(required = false) Book book);

serviceImpl 类

只需要将里面的实体类换一下即可

@Override
public PageResult<Book> getAll(PageParams pageParams, Book book) {
   // 拼装查询条件
   LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper<>();
   // 根据名称模糊查询,在 sql 中拼接 course_base.name like '% 值 %'
   queryWrapper.like(StringUtils.isNotEmpty(book.getName()),Book::getName,book.getName());
   // 根据课程审核状态查询 course_base.audit_status = ?
   queryWrapper.eq(StringUtils.isNotEmpty(book.getName()), Book::getDel,"0");
   // 创建 page 分页参数对象,参数:当前页码,每页记录数
   Page<Book> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
   // 开始进行分页查询
   Page<Book> pageResult = bookMapper.selectPage(page, queryWrapper);
   // 数据列表
   List<Book> items = pageResult.getRecords();
   // 总记录数
   long total = pageResult.getTotal();
   PageResult<Book> courseBasePageResult = new PageResult<>(items,total,pageParams.getPageNo(), pageParams.getPageSize());
   return  courseBasePageResult;
}

Controller 类

到现在后端分页就完毕了,剩下的就是前端拿数据然后再分页展示的事儿了

@PostMapping("course/list")
public PageResult<Book> list(PageParams pageParams, @RequestBody Book book)
{
   PageResult<Book> courseBasePageResult = bookService.getAll(pageParams, book);
   return courseBasePageResult;
}

# 前端分页

const content = document.querySelector('#content') // 展示区域
const shu = document.querySelector('.shu') // 触发查询事件后获取内容的
const queryShu = document.querySelector('#queryShu') // 查询按钮 点击后触发事件的
let pageNo = 1// 当前页
let pageSize = 5// 总获取数据量 (后端请求的)
let pageSize1 = 2// 总展示数据量 (前端展示的)
const url1 = `http://localhost/star/b/course/list?pageNo=${pageNo}&pageSize=${pageSize}`
queryShu.addEventListener('click', function() {
    axios(url1, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        data: {
            name: shu.value
        }
    })
    .then(r => {
        let totalPage = Math.ceil(r.data.items.length / pageSize1)
        let lis = ''
        let li = ''
        function changePage(newPage) {
            pageNo = newPage
            r.data.items.forEach(function(item, index) {
                let starIndex = (pageNo - 1) * pageSize1
                let endIndex = Math.min(pageNo * pageSize1 - 1, r.data.items.length - 1)
                if(index >= starIndex && index <= endIndex)
                    li += '<tr>'+
                        '<th>'+ item.id +'</th>'
                        + '<th>'+ item.type +'</th>'
                        + '<th>'+ item.name +'</th>'
                        + '<th>'+ item.auth +'</th>'
                        + '<th>'+ item.chu +'</th>'
                        + '<th>'+ item.count +'</th>'
                        + '<th>'+ '<button onclick="delt(this)">删除</button>' +'</th>'
                        + '<th>'+ '<button onclick="upd(this)">修改</button>' +'</th>'
                        +'</tr>'
                })
                lis += li
                content.innerHTML = lis
                // 更新总页数显示
                $('#totalPage').text(totalPage);// 显示总页数
                $('#currentPage').text(pageNo)// 显示当前页数
        }
        // 上一页按钮点击事件
        $('#prevBtn').click(function () {
            if (pageNo > 1) {
                pageNo--
                changePage(pageNo); // 切换到上一页
            }
        });
        // 下一页按钮点击事件
        $('#nextBtn').click(function () {
            if (pageNo < totalPage) {
                pageNo++
                changePage(pageNo); // 切换到下一页
            }
        });
        // 跳转 n 页
        $('#jumpBtn').click(function(){
            let num = $('#jumpInput').val();
            if(num >= 1 && num <= totalPage){
                changePage(num)
            }else{
                changePage(pageNo)
            }
        })
        // 执行调用方法并传入当前页的初始值
        changePage(pageNo)
    })
    .catch(e => {
        console.log(e)
    })
})

html 按钮部分

<div class="Page">
   <button id="prevBtn">上一页</button>
   <button id="nextBtn">下一页</button>
   <span id="currentPage">1</span> / <span id="totalPage">1</span>
   <input type="number" id="jumpInput" min="1" max="1" />
   <button id="jumpBtn">跳转</button>
</div>