在做SpringBoot后端项目时,我想采用后端分页的模式,后端分页是在后端先把数据处理好,再发给前端,前端只需要访问对应的页面拿相应页的数据即可。后端分页的写法中MyBatis和JPA都有现成的后端分页组件,而JdbcTemplate却没有。因此这里以实体类User为例把自己的学习过程记录下来。
电脑操作系统:Win10
Java版本:JDK1.8
MySQL数据库版本:mysql-8.0.26-winxx64
编辑器:IntelliJ IDEA 2021.2 企业版
SpringBoot版本:2.7.2
工作目录
<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.0modelVersion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.7.2version>
<relativePath/>
parent>
<groupId>com.examplegroupId>
<artifactId>pagingQueryartifactId>
<version>0.0.1-SNAPSHOTversion>
<name>pagingQueryname>
<description>Demo project for Spring Bootdescription>
<properties>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-jdbcartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<scope>runtimescope>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
exclude>
excludes>
configuration>
plugin>
plugins>
build>
project>
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/jdbcTemplate?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# thymeleaf配置
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
# 创建数据库
CREATE DATABASE `jdbcTemplate`CHARACTER SET utf8 COLLATE utf8_general_ci;
# 创建user表
CREATE TABLE `jdbctemplate`.`user`( `id` INT(4) UNSIGNED NOT NULL, `username` VARCHAR(30) NOT NULL, `password` VARCHAR(30) NOT NULL, `email` VARCHAR(30), `gender` INT(1), PRIMARY KEY (`id`) ) ENGINE=INNODB CHARSET=utf8 COLLATE=utf8_general_ci;
#向user表中插入数据
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('1', 'AAA', 'pwd01', '[email protected]', '1');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('2', 'BBB', 'pwd02', '[email protected]', '2');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('3', 'CCC', 'pwd03', '[email protected]', '3');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`) VALUES ('4', 'DDD', 'pwd04', '[email protected]', '0');
UPDATE `jdbctemplate`.`user` SET `gender` = '0' WHERE `id` = '2';
UPDATE `jdbctemplate`.`user` SET `gender` = '1' WHERE `id` = '3';
UPDATE `jdbctemplate`.`user` SET `birth` = '1994-07-16' WHERE `id` = '4';
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('5', 'EEE', 'pwd05', '[email protected]', '0');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('6', 'FFF', 'pwd06', '[email protected]', '1');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('7', 'GGG', 'pwd07', '[email protected]', '1');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('8', 'HHH', 'pwd08', '[email protected]', '0');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('9', 'III', 'pwd09', '[email protected]', '1');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('10', 'JJJ', 'pwd10', '[email protected]', '0');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('11', 'KKK', 'pwd11', '[email protected]', '0');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('12', 'LLL', 'pwd12', '[email protected]', '1');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('13', 'MMM', 'pwd13', '[email protected]', '0');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('14', 'NNN', 'pwd14', '[email protected]', '1');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `gender`, `birth`) VALUES ('15', 'OOO', 'pwd15', '0');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`) VALUES ('16', 'PPP', 'pwd16', '[email protected]');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`) VALUES ('17', 'QQQ', 'pwd17', '[email protected]', '1');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('18', 'RRR', 'pwd18', '[email protected]', '0');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `birth`) VALUES ('19', 'SSS', 'pwd19', '[email protected]');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('20', 'TTT', 'pwd20', '[email protected]', '1');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('21', 'UUU', 'pwd21', '[email protected]', '0');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`) VALUES ('22', 'VVV', 'pwd22', '[email protected]', '1');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`) VALUES ('23', 'WWW', 'pwd23', '[email protected]');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `gender`) VALUES ('24', 'XXX', 'pwd24', '0');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('25', 'YYY', 'pwd25', '[email protected]', '1');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`) VALUES ('26', 'ZZZ', 'pwd26', '[email protected]');
UPDATE `jdbctemplate`.`user` SET `gender` = '0' WHERE `id` = '16';
UPDATE `jdbctemplate`.`user` SET `gender` = '1' WHERE `id` = '19';
UPDATE `jdbctemplate`.`user` SET `gender` = '0' WHERE `id` = '23';
UPDATE `jdbctemplate`.`user` SET `gender` = '1' WHERE `id` = '26';
创建后User表如下图所示:
package com.example.pagingQuery;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
@SpringBootTest
class PagingQueryApplicationTests {
//DI注入数据源
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
//看一下默认数据源
System.out.println(dataSource.getClass());
//获得连接
Connection connection = dataSource.getConnection();
System.out.println(connection);
//关闭连接
connection.close();
}
}
运行测试是否运行成功,如果成功,则说明成功连接数据库。
package com.example.pagingQuery.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String username;
private String password;
private String email;
private Integer gender;//0:女性 1:男性
}
package com.example.pagingQuery.dao;
import com.example.pagingQuery.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.GetMapping;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Repository
public class UserDao {
@Autowired
JdbcTemplate jdbcTemplate;
//获取所有的user信息
public List<User> getUserList() throws ParseException {
String sql = "select * from `user`";
List<Map<String, Object>> userList = jdbcTemplate.queryForList(sql);
ArrayList<User> users = new ArrayList<>();
for (int i = 0; i < userList.size(); i++) {
int id = ((Number) userList.get(i).get("id")).intValue();
String username = (String) userList.get(i).get("username");
String password = (String) userList.get(i).get("password");
String email = (String) userList.get(i).get("email");
int gender = ((Number) userList.get(i).get("gender")).intValue();
User user = new User(id, username, password, email, gender);
users.add(user);
}
return users;
}
}
package com.example.pagingQuery.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
//添加视图控制器
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/index").setViewName("userList");
}
}
静态资源使用Bootstrap v3,获取静态资源链接(永久有效):
链接:https://pan.baidu.com/s/1AShqyIhCPCR1t9qbpaoJJg
提取码:Msql
注意:下面给的是静态页面
DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<link rel="stylesheet" href="../static/bootstrap-3.4.1-dist/css/bootstrap.min.css" th:href="@{/bootstrap-3.4.1-dist/css/bootstrap.min.css}">
<link rel="stylesheet" href="../static/bootstrap-3.4.1-dist/css/bootstrap.min.css.map" th:href="@{/bootstrap-3.4.1-dist/css/bootstrap.min.css.map}">
<style>
.table-wrapper{
min-height: 300px;
}
.paging{
width: 100%;
height: 150px;
position: relative;
}
.paging nav{
display: block;
margin: auto;
position: absolute;
left: 600px;
top: 30px;
}
style>
head>
<body>
<div class="panel panel-default">
<div class="panel-heading">Panel headingdiv>
<div class="panel-body">
<p>《甄嬛传》永远滴神p>
div>
<div class="table-wrapper">
<table class="table table-striped">
<thead>
<tr>
<th>序号th>
<th>用户名th>
<th>密码th>
<th>邮箱th>
<th>性别th>
tr>
thead>
<tbody>
<tr>
<td>1td>
<td>AAAtd>
<td>123456td>
<td>[email protected]td>
<td>男td>
tr>
<tr>
<td>2td>
<td>BBBtd>
<td>123456td>
<td>[email protected]td>
<td>男td>
tr>
<tr>
<td>3td>
<td>CCCtd>
<td>123456td>
<td>[email protected]td>
<td>男td>
tr>
<tr>
<td>4td>
<td>DDDtd>
<td>123456td>
<td>[email protected]td>
<td>男td>
tr>
<tr>
<td>5td>
<td>EEEtd>
<td>123456td>
<td>[email protected]td>
<td>男td>
tr>
<tr>
<td>6td>
<td>FFFtd>
<td>123456td>
<td>[email protected]td>
<td>男td>
tr>
<tr>
<td>7td>
<td>GGGtd>
<td>123456td>
<td>[email protected]td>
<td>男td>
tr>
tbody>
table>
div>
<div class="paging">
<nav aria-label="Page navigation">
<ul class="pagination pagination-lg">
<li>
<a href="#" aria-label="Previous">
<span aria-hidden="true">«span>
a>
li>
<li><a href="#">1a>li>
<li><a href="#">2a>li>
<li><a href="#">3a>li>
<li><a href="#">4a>li>
<li><a href="#">5a>li>
<li>
<a href="#" aria-label="Next">
<span aria-hidden="true">»span>
a>
li>
ul>
nav>
div>
div>
body>
html>
静态页面效果如下图所示:
package com.example.pagingQuery.controller;
import com.example.pagingQuery.dao.UserDao;
import com.example.pagingQuery.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.text.ParseException;
import java.util.List;
@Controller
public class UserController {
@Autowired
UserDao userDao;
@GetMapping("/index")
public String showList(Model model){
List<User> users = userDao.getUserList();
model.addAttribute("users",users);
return "userList";
}
}
DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<link rel="stylesheet" href="../static/bootstrap-3.4.1-dist/css/bootstrap.min.css" th:href="@{/bootstrap-3.4.1-dist/css/bootstrap.min.css}">
<link rel="stylesheet" href="../static/bootstrap-3.4.1-dist/css/bootstrap.min.css.map" th:href="@{/bootstrap-3.4.1-dist/css/bootstrap.min.css.map}">
<style>
.table-wrapper{
min-height: 300px;
}
.paging{
width: 100%;
height: 150px;
position: relative;
}
.paging nav{
display: block;
margin: auto;
position: absolute;
left: 600px;
top: 30px;
}
style>
head>
<body>
<div class="panel panel-default">
<div class="panel-heading">Panel headingdiv>
<div class="panel-body">
<p>《甄嬛传》永远滴神p>
div>
<div class="table-wrapper">
<table class="table table-striped">
<thead>
<tr>
<th>序号th>
<th>用户名th>
<th>密码th>
<th>邮箱th>
<th>性别th>
tr>
thead>
<tbody>
<tr th:each="user:${users}">
<td th:text="${user.getId()}">td>
<td th:text="${user.getUsername()}">td>
<td th:text="${user.getPassword()}">td>
<td th:text="${user.getEmail()}">td>
<td th:text="${user.getGender()==0?'女':'男'}">td>
tr>
tbody>
table>
div>
<div class="paging">
<nav aria-label="Page navigation">
<ul class="pagination pagination-lg">
<li>
<a href="#" aria-label="Previous">
<span aria-hidden="true">«span>
a>
li>
<li><a href="#">1a>li>
<li><a href="#">2a>li>
<li><a href="#">3a>li>
<li><a href="#">4a>li>
<li><a href="#">5a>li>
<li>
<a href="#" aria-label="Next">
<span aria-hidden="true">»span>
a>
li>
ul>
nav>
div>
div>
body>
html>
运行程序,得到动态页面效果如下图所示:
这个时候准备工作算是完成,下面开始进行分页工作
首先创建PageList类,代表每一页
package com.example.pagingQuery.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.ArrayList;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class PageList<T> {
private int pageSize; //单页最大数据量
private int dataNumber; //Java类T 总的数据量
private int pageNumber; //总的页数 总的页数=(总的数据量%单页最大数据量)==0?(总的数据量/单页最大数据量):((总的数据量/单页最大数据量)+1)
private int currentPage; //当前页
private List<T> dataList = new ArrayList<T>(); //当前页的全部数据
public PageList(int currentPage,int pageSize,int dataNumber){
this.currentPage = currentPage;
this.pageSize = pageSize;
pageNumber = (dataNumber%pageSize==0?(dataNumber/pageSize):(dataNumber/pageSize+1));
}
}
在UserDao里面添加一个分页的方法,根据前端页面传来的单页页面数据大小和当前页返回数据列表
//分页功能实现,获取分页数据
//前端页面点击分页器时调用此函数
public PageList<User> getUserListByPage(int currentPage,int pageSize){
//获取总数据量
List<User> userList = getUserList();
int dataNumber = userList.size();
//设置当前页面和每个页面的最大数据量
//这里我设置每个页面的最大数据量为7
PageList<User> userPageList = new PageList<>(currentPage, pageSize,dataNumber);
//获取所有的user数据,易知总的数据量为26
userPageList.setDataNumber(jdbcTemplate.queryForObject("SELECT count(id) FROM `user`",Integer.class));
//根据当前页的情况来确定当前页的展示数据列表
if (userPageList.getCurrentPage()==userPageList.getPageNumber()){
//当前页为总页面的最后一页
userPageList.setDataList(jdbcTemplate.query("SELECT * FROM `user` limit ?,?",new BeanPropertyRowMapper<>(User.class),
(currentPage-1)*pageSize,userPageList.getDataNumber()-(currentPage-1)*pageSize));
}else {
userPageList.setDataList(jdbcTemplate.query("SELECT * FROM `user` limit ?,?",new BeanPropertyRowMapper<>(User.class),
(currentPage-1)*pageSize,pageSize));
}
return userPageList;
}
主要是对分页器那边进行修改,使用JS进行页面处理
DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<link rel="stylesheet" href="../static/bootstrap-3.4.1-dist/css/bootstrap.min.css" th:href="@{/bootstrap-3.4.1-dist/css/bootstrap.min.css}">
<link rel="stylesheet" href="../static/bootstrap-3.4.1-dist/css/bootstrap.min.css.map" th:href="@{/bootstrap-3.4.1-dist/css/bootstrap.min.css.map}">
<style>
.table-wrapper{
min-height: 300px;
}
.paging{
width: 100%;
height: 150px;
position: relative;
}
.paging nav{
display: block;
margin: auto;
position: absolute;
left: 600px;
top: 30px;
}
style>
head>
<body>
<div class="panel panel-default">
<div class="panel-heading">Panel headingdiv>
<div class="panel-body">
<p>《甄嬛传》永远滴神p>
div>
<div class="table-wrapper">
<table class="table table-striped">
<thead>
<tr>
<th>序号th>
<th>用户名th>
<th>密码th>
<th>邮箱th>
<th>性别th>
tr>
thead>
<tbody>
<tr th:each="userByPage:${usersByPage}">
<td th:text="${userByPage.getId()}">td>
<td th:text="${userByPage.getUsername()}">td>
<td th:text="${userByPage.getPassword()}">td>
<td th:text="${userByPage.getEmail()}">td>
<td th:text="${userByPage.getGender()==0?'女':'男'}">td>
tr>
tbody>
table>
div>
<div class="paging">
<div id="pageNumber" th:text="${pageNumber}" style="display: none">div>
<nav aria-label="Page navigation">
<ul id="sorter" class="pagination pagination-lg">
ul>
nav>
div>
div>
<script>
window.onload = function (){
//获取pageNumber
let pageNumber = document.getElementById("pageNumber");
let number = parseInt(pageNumber.innerText);
//获取ul对象
let sorter = document.getElementById("sorter");
sorter.innerHTML += ' ';
for (let i = 0; i < number; i++) {
sorter.innerHTML += '+ (i+1)+ '">' + (i+1) + '';
}
sorter.innerHTML += ' ';
}
script>
body>
html>
package com.example.pagingQuery.controller;
import com.example.pagingQuery.dao.UserDao;
import com.example.pagingQuery.pojo.PageList;
import com.example.pagingQuery.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import java.text.ParseException;
import java.util.List;
@Controller
public class UserController {
@Autowired
UserDao userDao;
@GetMapping("/index")
public String showList(Model model){
List<User> users = userDao.getUserList();
model.addAttribute("users",users);
return "userList";
}
@GetMapping("/user/{pageSize}/{currentPage}")
public PageList<User> UserPageList(@PathVariable("pageSize") int pageSize,@PathVariable("currentPage") int currentPage){
return userDao.getUserListByPage(currentPage,pageSize);
}
@GetMapping({"/user/listByPage/{currentPage}","localhost:8080/user/listByPage/{currentPage}"})
public String showListByPage(@PathVariable("currentPage") int currentPage,Model model){
PageList<User> userPageList = UserPageList(7, currentPage);
//起不同的名,与showList区分一下
List<User> usersByPage = userPageList.getDataList();
model.addAttribute("usersByPage",usersByPage);
//获取总的页数
int pageNumber = userPageList.getPageNumber();
model.addAttribute("pageNumber",pageNumber);
return "userList";
}
}
访问链接:localhost:8080/user/listByPage/1
效果图1
效果图2
效果图3
效果图4