在做SpringBoot后端项目时,我想采用后端分页的模式,后端分页是在后端先把数据处理好,再发给前端,前端只需要访问对应的页面拿相应页的数据即可。后端分页的写法中MyBatis和JPA都有现成的后端分页组件,而JdbcTemplate却没有。因此这里以实体类User为例把自己的学习过程记录下来。
<?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>
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', 'test01@qq.com', '1');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('2', 'BBB', 'pwd02', 'test02@qq.com', '2');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('3', 'CCC', 'pwd03', 'test03@qq.com', '3');
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');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('6', 'FFF', 'pwd06', 'test06@qq.com', '1');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('7', 'GGG', 'pwd07', 'test07@qq.com', '1');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('8', 'HHH', 'pwd08', 'test08@qq.com', '0');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('9', 'III', 'pwd09', 'test09@qq.com', '1');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('10', 'JJJ', 'pwd10', 'test10@qq.com', '0');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('11', 'KKK', 'pwd11', 'test11@qq.com', '0');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('12', 'LLL', 'pwd12', 'test12@qq.com', '1');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('13', 'MMM', 'pwd13', 'test13@qq.com', '0');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('14', 'NNN', 'pwd14', 'test14@qq.com', '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', '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');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `birth`) VALUES ('19', 'SSS', 'pwd19', 'test19@qq.com');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('20', 'TTT', 'pwd20', 'test20@qq.com', '1');
INSERT INTO `jdbctemplate`.`user` (`id`, `username`, `password`, `email`, `gender`, `birth`) VALUES ('21', 'UUU', 'pwd21', 'test21@qq.com', '0');
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');
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表如下图所示:
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/1oq17a4uodSNYWwYNMfjIVw 提取码:Msql
注意:下面给的是静态页面
<!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>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>AAA</td>
<td>123456</td>
<td>test01@qq.com</td>
<td>男</td>
</tr>
<tr>
<td>2</td>
<td>BBB</td>
<td>123456</td>
<td>test02@qq.com</td>
<td>男</td>
</tr>
<tr>
<td>3</td>
<td>CCC</td>
<td>123456</td>
<td>test03@qq.com</td>
<td>男</td>
</tr>
<tr>
<td>4</td>
<td>DDD</td>
<td>123456</td>
<td>test04@qq.com</td>
<td>男</td>
</tr>
<tr>
<td>5</td>
<td>EEE</td>
<td>123456</td>
<td>test05@qq.com</td>
<td>男</td>
</tr>
<tr>
<td>6</td>
<td>FFF</td>
<td>123456</td>
<td>test06@qq.com</td>
<td>男</td>
</tr>
<tr>
<td>7</td>
<td>GGG</td>
<td>123456</td>
<td>test07@qq.com</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="#">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">»</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>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>
</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="#">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">»</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>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>
</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">
<!-- 自定义一个容器,用于存放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">«</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">»</span></a></li>'; } </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
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/183978.html原文链接:https://javaforall.cn