Springboot整合JdbcTemplate实现分页查询

250 阅读5分钟

Springboot整合JdbcTemplate实现分页查询

一、前言

在做SpringBoot后端项目时,我想采用后端分页的模式,后端分页是在后端先把数据处理好,再发给前端,前端只需要访问对应的页面拿相应页的数据即可。后端分页的写法中MyBatis和JPA都有现成的后端分页组件,而JdbcTemplate却没有。因此这里以实体类User为例把自己的学习过程记录下来。

二、开发工具及环境

  • 电脑操作系统:Win10
  • Java版本:JDK1.8
  • MySQL数据库版本:mysql-8.0.26-winxx64
  • 编辑器:IntelliJ IDEA 2021.2 企业版
  • SpringBoot版本:2.7.2
  • 工作目录

LHSglcAvMtEiVYQ.png

三、SpringBoot基本配置

1、Spring initializr 设置

image-20220806150122017.png

2、pom.xml

 <?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.7.2</version>
         <relativePath/> <!-- lookup parent from repository -->
     </parent>
     <groupId>com.example</groupId>
     <artifactId>pagingQuery</artifactId>
     <version>0.0.1-SNAPSHOT</version>
     <name>pagingQuery</name>
     <description>Demo project for Spring Boot</description>
     <properties>
         <java.version>1.8</java.version>
     </properties>
     <dependencies>
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-jdbc</artifactId>
         </dependency>
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-thymeleaf</artifactId>
         </dependency>
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-web</artifactId>
         </dependency>
 ​
         <dependency>
             <groupId>mysql</groupId>
             <artifactId>mysql-connector-java</artifactId>
             <scope>runtime</scope>
         </dependency>
         <dependency>
             <groupId>org.projectlombok</groupId>
             <artifactId>lombok</artifactId>
             <optional>true</optional>
         </dependency>
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-test</artifactId>
             <scope>test</scope>
         </dependency>
     </dependencies>
 ​
     <build>
         <plugins>
             <plugin>
                 <groupId>org.springframework.boot</groupId>
                 <artifactId>spring-boot-maven-plugin</artifactId>
                 <configuration>
                     <excludes>
                         <exclude>
                             <groupId>org.projectlombok</groupId>
                             <artifactId>lombok</artifactId>
                         </exclude>
                     </excludes>
                 </configuration>
             </plugin>
         </plugins>
     </build>
 ​
 </project>

3、application.properties

 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
  • 这里我用的数据库名为jdbcTemplate
  • MySQL 8.xx的版本需要设时区serverTimezone

四、准备工作-数据库

1、创建数据库及User表

 # 创建数据库
 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), `birth` DATE, 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', 'test01@qq.com', '1', '1999-03-26'); 
 INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('2', 'BBB', 'pwd02', 'test02@qq.com', '2', '2001-11-15'); 
 INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('3', 'CCC', 'pwd03', 'test03@qq.com', '3', '2004-07-07'); 
 INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`) VALUES ('4', 'DDD', 'pwd04', 'test04@qq.com', '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', 'test05@qq.com', '0', '2002-06-14'); 
 INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('6', 'FFF', 'pwd06', 'test06@qq.com', '1', '2003-05-08'); 
 INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('7', 'GGG', 'pwd07', 'test07@qq.com', '1', '1991-12-27'); 
 INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('8', 'HHH', 'pwd08', 'test08@qq.com', '0', '2006-02-16'); 
 INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('9', 'III', 'pwd09', 'test09@qq.com', '1', '1998-04-09'); 
 INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('10', 'JJJ', 'pwd10', 'test10@qq.com', '0', '1997-07-24'); 
 INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('11', 'KKK', 'pwd11', 'test11@qq.com', '0', '1995-01-28'); 
 INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('12', 'LLL', 'pwd12', 'test12@qq.com', '1', '1995-01-28'); 
 INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('13', 'MMM', 'pwd13', 'test13@qq.com', '0', '1995-07-21'); 
 INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('14', 'NNN', 'pwd14', 'test14@qq.com', '1', '1994-03-25'); 
 INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `gender`, `birth`) VALUES ('15', 'OOO', 'pwd15', '0', '1991-12-30'); 
 INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`) VALUES ('16', 'PPP', 'pwd16', 'test16@qq.com'); 
 INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`) VALUES ('17', 'QQQ', 'pwd17', 'test17@qq.com', '1'); 
 INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('18', 'RRR', 'pwd18', 'test18@qq.com', '0', '2000-02-25'); 
 INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `birth`) VALUES ('19', 'SSS', 'pwd19', 'test19@qq.com', '1999-12-31'); 
 INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('20', 'TTT', 'pwd20', 'test20@qq.com', '1', '2000-07-14'); 
 INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('21', 'UUU', 'pwd21', 'test21@qq.com', '0', '1995-07-14'); 
 INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`) VALUES ('22', 'VVV', 'pwd22', 'test22@qq.com', '1'); 
 INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`) VALUES ('23', 'WWW', 'pwd23', 'test23@qq.com'); 
 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', 'test25@qq.com', '1', '1981-11-06');
 INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`) VALUES ('26', 'ZZZ', 'pwd26', 'test26@qq.com');
 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表如下图所示:

Jg4Phucx9ieNW3t.png

2、测试是否能连接上数据库

 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();
     }
 ​
 }

运行测试是否运行成功,如果成功,则说明成功连接数据库。

五、架构准备

1、User类

 package com.example.pagingQuery.pojo;
 ​
 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:男性
     private Date birth;
 }

2、UserDao

 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();
 ​
             SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
             Date birth = dateFormat.parse((String) userList.get(i).get("birth"));
 ​
             User user = new User(id, username, password, email, gender, birth);
             users.add(user);
         }
 ​
         return users;
     }
 }

3、视图控制器MyMvcConfig

 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("/").setViewName("userlist");
     }
 }
 ​

4、静态资源

静态资源使用Bootstrap v3,获取静态资源链接(永久有效):

链接:pan.baidu.com/s/1oq17a4uo… 提取码:Msql

5、userlist.html 静态页面

注意:下面给的是静态页面

 <!DOCTYPE html>
 <html lang="en" xmlns:th="http://www.thymeleaf.org">
 <head>
     <meta charset="UTF-8">
     <title>Title</title>
     <!-- 引入Bootstrap v3 静态资源-->
     <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">
         <!-- Default panel contents -->
         <div class="panel-heading">Panel heading</div>
         <div class="panel-body">
             <p>《甄嬛传》永远滴神</p>
         </div>
 ​
         <!-- Table -->
         <div class="table-wrapper">
             <table class="table table-striped">
                 <thead>
                 <tr>
                     <th>序号</th>
                     <th>用户名</th>
                     <th>密码</th>
                     <th>邮箱</th>
                     <th>性别</th>
                     <th>生日</th>
                 </tr>
                 </thead>
                 <tbody>
                 <tr>
                     <td>1</td>
                     <td>AAA</td>
                     <td>123456</td>
                     <td>test01@qq.com</td>
                     <td></td>
                     <td>2001-07-03</td>
                 </tr>
                 <tr>
                     <td>2</td>
                     <td>BBB</td>
                     <td>123456</td>
                     <td>test02@qq.com</td>
                     <td></td>
                     <td>2001-07-03</td>
                 </tr>
                 <tr>
                     <td>3</td>
                     <td>CCC</td>
                     <td>123456</td>
                     <td>test03@qq.com</td>
                     <td></td>
                     <td>2001-07-03</td>
                 </tr>
                 <tr>
                     <td>4</td>
                     <td>DDD</td>
                     <td>123456</td>
                     <td>test04@qq.com</td>
                     <td></td>
                     <td>2001-07-03</td>
                 </tr>
                 <tr>
                     <td>5</td>
                     <td>EEE</td>
                     <td>123456</td>
                     <td>test05@qq.com</td>
                     <td></td>
                     <td>2001-07-03</td>
                 </tr>
                 <tr>
                     <td>6</td>
                     <td>FFF</td>
                     <td>123456</td>
                     <td>test06@qq.com</td>
                     <td></td>
                     <td>2001-07-03</td>
                 </tr>
                 <tr>
                     <td>7</td>
                     <td>GGG</td>
                     <td>123456</td>
                     <td>test07@qq.com</td>
                     <td></td>
                     <td>2001-07-03</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">&laquo;</span>
                         </a>
                     </li>
                     <li><a href="#">1</a></li>
                     <li><a href="#">2</a></li>
                     <li><a href="#">3</a></li>
                     <li><a href="#">4</a></li>
                     <li><a href="#">5</a></li>
                     <li>
                         <a href="#" aria-label="Next">
                             <span aria-hidden="true">&raquo;</span>
                         </a>
                     </li>
                 </ul>
             </nav>
         </div>
     </div>
 ​
 </body>
 </html>

静态页面效果如下图所示:

WeqtE6A8Q3huVBg.png

6、UserController类

 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("/")
     public String showList(Model model){
         List<User> users = userDao.getUserList();
         model.addAttribute("users",users);
         return "userlist";
     }
 }

7、userlist.html 动态页面

 <!DOCTYPE html>
 <html lang="en" xmlns:th="http://www.thymeleaf.org">
 <head>
     <meta charset="UTF-8">
     <title>Title</title>
     <!-- 引入Bootstrap v3 静态资源-->
     <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">
         <!-- Default panel contents -->
         <div class="panel-heading">Panel heading</div>
         <div class="panel-body">
             <p>《甄嬛传》永远滴神</p>
         </div>
 ​
         <!-- Table -->
         <div class="table-wrapper">
             <table class="table table-striped">
                 <thead>
                 <tr>
                     <th>序号</th>
                     <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>
                     <td th:text="${#dates.format(user.getBirth(),'yyyy-MM-dd')}"></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">&laquo;</span>
                         </a>
                     </li>
                     <li><a href="#">1</a></li>
                     <li><a href="#">2</a></li>
                     <li><a href="#">3</a></li>
                     <li><a href="#">4</a></li>
                     <li><a href="#">5</a></li>
                     <li>
                         <a href="#" aria-label="Next">
                             <span aria-hidden="true">&raquo;</span>
                         </a>
                     </li>
                 </ul>
             </nav>
         </div>
     </div>
 ​
 </body>
 </html>

运行程序,得到动态页面效果如下图所示:

vFWmAGpUNOEuYyf.png

这个时候准备工作算是完成,下面开始进行分页工作

六、分页功能实现研究

1、创建PageList类

首先创建PageList类,代表每一页

 package com.example.pagingQuery.pojo;
 ​
 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));
     }
 ​
 }
  • currentPage:当前页,指的实际上是用户点击某一页时我们要展现出的目标页
  • dataNumber和pageSize主要的用处就是计算出总的页数
  • dataList用于存储我们要展现给用户的数据列表

2、UserDao分页方法

在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;
 }

3、userlist.html页面修改

主要是对分页器那边进行修改,使用JS进行页面处理

 <!DOCTYPE html>
 <html lang="en" xmlns:th="http://www.thymeleaf.org">
 <head>
     <meta charset="UTF-8">
     <title>Title</title>
     <!-- 引入Bootstrap v3 静态资源-->
     <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">
         <!-- Default panel contents -->
         <div class="panel-heading">Panel heading</div>
         <div class="panel-body">
             <p>《甄嬛传》永远滴神</p>
         </div>
 ​
         <!-- Table -->
         <div class="table-wrapper">
             <table class="table table-striped">
                 <thead>
                 <tr>
                     <th>序号</th>
                     <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>
                     <td th:text="${#dates.format(userByPage.getBirth(),'yyyy-MM-dd')}"></td>
                 </tr>
                 </tbody>
             </table>
         </div>
 ​
         <!-- 分页 -->
         <div class="paging">
             <!-- 自定义一个容器,用于存放pageNumber数据,并让此容器display:none;-->
             <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 += '<li><a href="#" aria-label="Previous"><span aria-hidden="true">&laquo;</span></a></li>';
         for (let i = 0; i < number; i++) {
             sorter.innerHTML += '<li><a href="' + (i+1)+ '">' + (i+1) + '</a></li>';
         }
         sorter.innerHTML += '<li><a href="#" aria-label="Previous"><span aria-hidden="true">&raquo;</span></a></li>';
     }
 </script>
 </body>
 </html>

4、UserController修改

 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("/")
     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";
     }
 ​
 }

5、展示效果图

访问链接:localhost:8080/user/listByPage/1,然后可以点击分页组件自由控制

效果图1

image-20220806172517496.png

效果图2

image-20220806172609134.png

效果图3

image-20220806172619180.png

效果图4

image-20220806172629665.png