这篇文章介绍一下怎么通过JQuery结合mybatis-plus的分页插件实现原生HTML页面的分页效果,没有使用任何前端框架,主要是对前端知识的应用。
创建Springboot项目
Intellij IDEA中创建一个Springboot项目,项目名为pager。
添加必须的依赖包
修改项目的pom.xml,添加一些基本的依赖:jdbc、mysql、mybatis、mybatis-plus、lombok、druid数据库连接池。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.5.9</version><relativePath /></parent><groupId>cn.edu.sgu.www</groupId><artifactId>pager</artifactId><version>0.0.1-SNAPSHOT</version><name>pager</name><description>jquey+mybatis-plus实现简单分页功能</description><properties><java.version>1.8</java.version><mysql.version>8.0.28</mysql.version><druid.version>1.1.21</druid.version><lombok.version>1.18.22</lombok.version><mybatis.version>2.2.2</mybatis.version><mybatis-plus.version>3.5.1</mybatis-plus.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!--lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>${lombok.version}</version></dependency><!--mysql--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>${mysql.version}</version></dependency><!--druid数据库连接池--><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>${druid.version}</version></dependency><!--mybatis--><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>${mybatis.version}</version></dependency><!--mybatis-plus--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>${mybatis-plus.version}</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>
添加数据源配置
将项目默认的配置文件application.properties重命名为application.yml。
添加启动端口、数据库、日志隔离级别的配置~
server:port: 8090logging:level:cn.edu.sgu.www.pager: debugspring:application:name: pagerdatasource:username: rootpassword: rooturl: jdbc:mysql://localhost:3306/pagerdriver-class-name: com.mysql.cj.jdbc.Drivertype: com.alibaba.druid.pool.DruidDataSource
准备数据库表
创建数据库pager,然后执行项目src/main/resources目录下的pager.sql脚本文件。
添加mybatis-plus分页插件
package cn.edu.sgu.www.pager.config;import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** Mybatis-Plus配置类* @author heyunlin* @version 1.0*/
@Configuration
public class MybatisPlusConfig {@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();// 添加分页插件interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return interceptor;}}
创建响应相关实体类
响应状态码枚举类
package cn.edu.sgu.www.pager.restful;/*** 响应状态码* @author heyunlin* @version 1.0*/
public enum ResponseCode {/*** 请求成功*/OK(200),/*** 失败的请求*/BAD_REQUEST(400),/*** 未授权*/UNAUTHORIZED(401),/*** 禁止访问*/FORBIDDEN(403),/*** 找不到*/NOT_FOUND(404),/*** 不可访问*/NOT_ACCEPTABLE(406),/*** 冲突*/CONFLICT(409),/*** 服务器发生异常*/ERROR(500);private final Integer value;ResponseCode(Integer value) {this.value = value;}public Integer getValue() {return value;}}
web响应实体类
package cn.edu.sgu.www.pager.restful;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;import java.io.Serializable;/*** @author heyunlin* @version 1.0*/
@Data
public class JsonResult<T> implements Serializable {private static final long serialVersionUID = 18L;/*** 响应数据*/private T data;/*** 响应状态码*/private Integer code;/*** 响应提示信息*/private String message;/*** 请求是否成功*/private boolean success;/*** 成功提示*/private static final String successMessage = "请求成功";public static <T> JsonResult<T> success(String message, T data) {JsonResult<T> jsonResult = new JsonResult<>();jsonResult.setCode(ResponseCode.OK.getValue());jsonResult.setMessage(message);jsonResult.setSuccess(true);jsonResult.setData(data);return jsonResult;}public static <T> JsonResult<JsonPage<T>> restPage(Page<T> page) {JsonPage<T> jsonPage = JsonPage.restPage(page);return success(successMessage, jsonPage);}}
分页查询结果
package cn.edu.sgu.www.pager.restful;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;import java.io.Serializable;
import java.util.List;/*** @author heyunlin* @version 1.0*/
@Data
public class JsonPage<T> implements Serializable {private static final long serialVersionUID = 18L;/*** 总记录数*/private Long total;/*** 查询结果*/private List<T> rows;/*** 根据Page对象构建JsonPage对象* @param page Page<T>* @return JsonPage<T>*/public static <T> JsonPage<T> restPage(Page<T> page) {JsonPage<T> jsonPage = new JsonPage<>();jsonPage.setTotal(page.getTotal());jsonPage.setRows(page.getRecords());return jsonPage;}}
分页参数的对象
package cn.edu.sgu.www.pager.restful;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;/*** @author heyunlin* @version 1.0*/
@Data
public class Pager<T> {/*** 页数*/private Integer page;/*** 每页的记录数*/private Integer rows;/*** 根据Pager创建Page对象* @param pager Pager* @return Page*/public static <T> Page<T> ofPage(Pager<T> pager) {return new Page<T>(pager.getPage(), pager.getRows());}}
创建数据库实体类
package cn.edu.sgu.www.pager.entity;import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;import java.io.Serializable;
import java.time.LocalDateTime;/*** @author heyunlin* @version 1.0*/
@Data
public class Song implements Serializable {private static final long serialVersionUID = 18L;private String id;/*** 歌曲名*/private String name;/*** 歌手*/private String singer;/*** 描述信息*/private String note;/*** 最后一次修改时间*/@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")private LocalDateTime lastUpdateTime;
}
创建持久层接口
继承mybatis-plus的BaseMapper接口
package cn.edu.sgu.www.pager.mapper;import cn.edu.sgu.www.pager.entity.Song;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;/*** @author heyunlin* @version 1.0*/
@Mapper
public interface SongMapper extends BaseMapper<Song> {}
创建业务层接口
SongService
package cn.edu.sgu.www.pager.service;import cn.edu.sgu.www.pager.entity.Song;
import cn.edu.sgu.www.pager.restful.Pager;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;/*** @author heyunlin* @version 1.0*/
public interface SongService {/*** 分页查询歌曲列表* @param pager 分页参数* @return Page<Song>*/Page<Song> selectByPage(Pager<Song> pager);
}
SongServiceImpl
package cn.edu.sgu.www.pager.service.impl;import cn.edu.sgu.www.pager.entity.Song;
import cn.edu.sgu.www.pager.mapper.SongMapper;
import cn.edu.sgu.www.pager.restful.Pager;
import cn.edu.sgu.www.pager.service.SongService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;/*** @author heyunlin* @version 1.0*/
@Service
public class SongServiceImpl implements SongService {private final SongMapper songMapper;@Autowiredpublic SongServiceImpl(SongMapper songMapper) {this.songMapper = songMapper;}@Overridepublic Page<Song> selectByPage(Pager<Song> pager) {Page<Song> page = Pager.ofPage(pager);return songMapper.selectPage(page, null);}}
创建控制器类
package cn.edu.sgu.www.pager.controller;import cn.edu.sgu.www.pager.entity.Song;
import cn.edu.sgu.www.pager.restful.JsonPage;
import cn.edu.sgu.www.pager.restful.JsonResult;
import cn.edu.sgu.www.pager.restful.Pager;
import cn.edu.sgu.www.pager.service.SongService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;/*** @author heyunlin* @version 1.0*/
@RestController
@RequestMapping(path = "/song", produces = "application/json;charset=utf-8")
public class SongController {private final SongService songService;@Autowiredpublic SongController(SongService songService) {this.songService = songService;}@GetMapping("/selectByPage")public JsonResult<JsonPage<Song>> selectByPage(Pager<Song> pager) {Page<Song> page = songService.selectByPage(pager);return JsonResult.restPage(page);}}
创建前端页面
song_list.html
在页面创建一个带标题的表格,然后在表格下方创建一个简单的分页组件~
可以调整每页显示几条数据,上一页、下一页、指定页数的跳转。
<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title>权限管理页面</title><script src="/js/jquery.min.js"></script><script src="/js/ajaxUtils.js"></script><script src="/js/song_list.js"></script><style>.table {height: 635px;overflow-y: scroll;border: 1px black solid;}#pageNum {width: 50px;}</style></head><body><div class="table"><table border="1"><thead>歌曲列表</thead><tbody id="song_list"></tbody></table></div><div>每页展示<select id="rows"></select>条记录 <button type="button" id="pre">上一页</button> 当前第<span id="page">1</span>页 <button type="button" id="next">下一页</button> 前往第<input type="number" id="pageNum" />页</div></body>
</html>
song_list.js
/*** 总页数*/
let total;
/*** 当前页*/
let page = 1;
/*** 每页显示的记录数*/
let rows = 15;
/*** 页码*/
let pageList = [15, 50 ,100, 200, 500];/*** 加载表格数据*/
function loadData() {/*** 表头*/let thead = "";/*** 表格体*/let tbody = "";thead += "<tr>";thead += "<th>歌曲ID</th>";thead += "<th>歌曲名</th>";thead += "<th>歌手</th>";thead += "<th>歌曲信息</th>";thead += "<th>最后一次修改时间</th>";thead += "</tr>";ajaxGet("/song/selectByPage", {page: page,rows: rows}, function (resp) {let data = resp.data;let list = data.rows;total = data.total;for (let i = 0; i < list.length; i++) {let data = list[i];tbody += "<tr>";tbody += "<td>" + data.id + "</td>";tbody += "<td>" + data.name + "</td>";tbody += "<td>" + data.singer + "</td>";tbody += "<td>" + data.note + "</td>";tbody += "<td>" + data.lastUpdateTime + "</td>";tbody += "</tr>";}$("#song_list").empty().append(thead + tbody);}, error);
}/*** 渲染分页组件*/
function fetchRows() {let options = "";for (let i = 0; i < pageList.length; i++) {let page = pageList[i];options += "<option value='" + page + "'>" + page + "</option>";}$("#rows").append(options);
}$(document).ready(function () {// 加载表格数据loadData();// 渲染分页组件fetchRows();/*** 绑定下拉框改变事件*/$("#rows").change(function () {// 设置每页记录数为下拉框的值rows = $(this).val();loadData();});/*** 上一页*/$("#pre").on("click", function () {if (page > 1) {page--;// 重新加载表格数据loadData();// 设置当前是第几页$("#page").html(page);}});/*** 下一页*/$("#next").on("click", function () {let maxPage = (total % rows) > 0 ? (total / rows + 1) : (total / rows);if (page <= maxPage - 1) {page++;// 重新加载表格数据loadData();// 设置当前是第几页$("#page").html(page);}});/*** 绑定键盘事件*/$("#pageNum").keydown(function () {let event = window.event;// 不允许输入空格if(event.keyCode === 32) {event.returnValue = false;} else if(event.keyCode === 13) {// 获取最大页数let maxPage = total % rows > 0 ? (total / rows + 1) : (total / rows);// 获取输入框内容let pageNum = parseInt($(this).val());// 修改页数page = pageNum > maxPage ? maxPage : pageNum;// 加载表格loadData();// 设置当前输入框的值$(this).val(page);// 设置当前在第几页$("#page").html(page);}});});
好了,文章就分享到这里了,需要代码的可以从git下载:
jquey+mybatis-plus实现简单分页功能https://gitee.com/muyu-chengfeng/pager.git