在SpringBoot或者Spring项目中实现最原始的分页功能
不得不感慨自己的写代码水平还是有很大的提升空间,甚至是我觉得很烂来形容吧,近两天一直有一个项目的分页功能很让我头疼,是一个关于SpringBoot的项目,因为可能平时实战项目做的少,由于是学生的原因吧,反正就是自己的不足,导致这个问题困扰着我,又因为忙着考研,所有最近也没时间花心思来慢慢写和整理,但是一直让我焦急万分啊,于是花了两个晚上细细斟酌别人的代码实现,然后开始啥都不看,自己手写实现全面的分页功能,到现在为止总算是小有所成吧,基本完成需求了。后面会学习PageHelper分页插件简化分页的复杂步骤,但是这种原始的写法,自己一定要随手捏来,十分锻炼水平,后面要更加努力的学习了早上再也不能睡到11点了,太颓废(小声逼逼晚上学习带玩熬夜太晚)哈哈哈!
下面是本次实现分页的代码部分:
首先需要一个关于分页的实体类来映射前后端数据,使其具有完整性,也把代码的冗余性降到了最低水准
package com.liuliu.web;
/**
* @author yuqiliu
* @create 2020-02-19 22:31
*/
import java.util.List;
public class Page<T> {
private int pageNo;//当前是第几页
private List<T> list; //当前显示的图书列表集合
private int pageSize = 3;//页面的尺寸数
public long getTotalItemNumber() {
return totalItemNumber;
}
private long totalItemNumber;//总的条目数
private int totalPageNumber;//总页数
public Page(int pageNo) {
super();
this.pageNo = pageNo;
}
public int getPageNo() {
if(pageNo < 0)
pageNo = 1;
if(pageNo > getTotalPageNumber()){
pageNo = getTotalPageNumber();
}
return pageNo;
}
public Page() {
}
public void setPageNo(int pageNo) {
this.pageNo = pageNo;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getPageSize() {
return pageSize;
}
public void setList(List<T> list) {
this.list = list;
}
public List<T> getList() {
return list;
}
public void setTotalPageNumber(int totalPageNumber) {
this.totalPageNumber = totalPageNumber;
}
public int getTotalPageNumber(){
totalPageNumber = (int)totalItemNumber / pageSize;
if(totalItemNumber % pageSize != 0){
totalPageNumber++;
}
return totalPageNumber;
}
public void setTotalItemNumber(long totalItemNumber) {
this.totalItemNumber = totalItemNumber;
}
public boolean isHasNext(){
if(getPageNo() < getTotalPageNumber()){
return true;
}
return false;
}
public boolean isHasPrev(){
if(getPageNo() > 1){
return true;
}
return false;
}
public int getPrevPage(){
if(isHasPrev()){
return getPageNo() - 1;
}
return getPageNo();
}
public int getNextPage(){
if(isHasNext()){
return getPageNo() + 1;
}
return getPageNo();
}
}
下面从Dao -> Service -> Controller重新梳理一遍我的结论过程
Book.java
package com.liuliu.pojo;
import java.sql.Date;
public class Book {
private Integer id;
private String author;
private String title;
private float price;
private Date publishingDate;
private int salesAmount;
private int storeNumber;
private String remark;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public Date getPublishingDate() {
return publishingDate;
}
public void setPublishingDate(Date publishingDate) {
this.publishingDate = publishingDate;
}
public int getSalesAmount() {
return salesAmount;
}
public void setSalesAmount(int salesAmount) {
this.salesAmount = salesAmount;
}
public int getStoreNumber() {
return storeNumber;
}
public void setStoreNumber(int storeNumber) {
this.storeNumber = storeNumber;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
@Override
public String toString() {
return "Book [id=" + id + ", author=" + author + ", title=" + title
+ ", price=" + price + ", publishingDate=" + publishingDate
+ ", salesAmount=" + salesAmount + ", storeNumber="
+ storeNumber + ", remark=" + remark + "]\n\n";
}
}
BookDao.java
package com.liuliu.mapper;
import com.liuliu.pojo.Book;
import com.liuliu.web.Page;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
/**
* @author yuqiliu
* @create 2020-02-19 0:18
*/
@Mapper
@Repository
public interface BookDAO {
//获取全部书籍
public List<Book> queryAllbook();
//分页查询操作
public Page selectByPage(int currentPage,int pageSize,HashMap<String,Object> map)throws SQLException;
//获取总的书籍数量
public int totalItemNumber();
//当页的数据
public List<Book> selectByPageItem(HashMap<String,Object> map);
}
BookMapper.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.liuliu.mapper.BookDAO">
<select id="queryAllbook" resultType="Book">
select * from bookstore.mybooks
</select>
<select id="selectByPageItem" resultType="Book" parameterType="map">
select * from bookstore.mybooks limit #{startIndex} ,#{pageSize}
</select>
<select id="totalItemNumber" resultType="int">
select count(*) from bookstore.mybooks
</select>
</mapper>
BookService.java
package com.liuliu.service;
import com.liuliu.pojo.Book;
import com.liuliu.web.Page;
import org.springframework.stereotype.Service;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
/**
* @author yuqiliu
* @create 2020-02-19 0:32
*/
@Service
public interface BookService {
public List<Book> queryAllbook();
public Page selectByPage(int currentPage,int pageSize,HashMap<String,Object> map)throws SQLException;
//---------------------------------------------------------------------------------------------------
//获取总的书籍数量
public int totalItemNumber();
//当页的数据
public List<Book> selectByPageItem(HashMap<String,Object> map);
}
BookServiceImpl.java
package com.liuliu.serviceImpl;
import com.liuliu.mapper.BookDAO;
import com.liuliu.pojo.Book;
import com.liuliu.service.BookService;
import com.liuliu.web.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author yuqiliu
* @create 2020-02-19 0:33
*/
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookDAO bookDAO;
@Override
public List<Book> queryAllbook() {
return null;
}
@Override
public Page selectByPage(int currentPage, int pageSize,HashMap<String,Object> map) throws SQLException {
Page<Book> page=new Page<>();
page.setPageNo(currentPage);
page.setPageSize(pageSize);
page.setTotalItemNumber(totalItemNumber());
int totalPageNumber=page.getTotalPageNumber();
page.setTotalPageNumber(totalPageNumber);
page.setList(selectByPageItem(map));
return page;
}
//-------------------------------------------------------------------------------------------------------
@Override
public int totalItemNumber() {
return bookDAO.totalItemNumber();
}
@Override
public List<Book> selectByPageItem(HashMap<String, Object> map) {
return bookDAO.selectByPageItem(map);
}
}
PageController.java
package com.liuliu.controller;
import com.liuliu.serviceImpl.BookServiceImpl;
import com.liuliu.web.Page;
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 javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
/**
* @author yuqiliu
* @create 2020-02-20 12:23
*/
@Controller
public class PageController {
@Autowired
private BookServiceImpl bookService;
@GetMapping("/toPage")
public String pageController(Integer currentPage, Integer pageSize, Model model, HttpServletRequest request) throws SQLException {
pageSize=3;
if(request.getParameter("currentPage")==null)
{
currentPage=1;
}
else
{
currentPage=Integer.parseInt(request.getParameter("currentPage"));
}
HashMap<String, Object> map = new HashMap<String, Object>();
System.out.println(currentPage);
map.put("startIndex",(currentPage-1)*pageSize);
map.put("pageSize",pageSize);
Page page = bookService.selectByPage(currentPage, pageSize,map);
model.addAttribute("pageBean",page);
return "index";
}
}
前端使用的是 Thymeleaf 模板引擎渲染
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>图书展示首页</title>
<style type="text/css">
.table{
width: 80%;
margin: auto;
}
.tableCenter{
text-align: center;
}
</style>
</head>
<body>
<form th:action="@{/toPage}" th:method="get">
<div class="tableCenter">
<table class="table" width="700" style="table-layout: fixed;">
<thead>
<th>ID</th>
<th>Author</th>
<th>Title</th>
<th>Price</th>
<th>PublishingDate</th>
<th>SalesAmount</th>
<th>StoreNumber</th>
<th>Remark</th>
</thead>
<tbody>
<tr th:each="Book:${pageBean.list}">
<td th:text="${Book.id}"></td>
<td th:text="${Book.author}"></td>
<td th:text="${Book.title}"></td>
<td th:text="${Book.price}"></td>
<td th:text="${Book.publishingDate}"></td>
<td th:text="${Book.salesAmount}"></td>
<td th:text="${Book.storeNumber}"></td>
<td th:text="${Book.remark}"></td>
</tr>
<tr>
<td colspan="8">
第 [[${pageBean.pageNo}]] / [[${pageBean.totalPageNumber}]]
每页显示[[${pageBean.pageSize}]]条
总的记录数[[${pageBean.totalItemNumber}]]
<a th:href="@{/toPage(currentPage=1)}" th:if="${pageBean.pageNo != 1 }">首页</a>
<a th:href="@{/toPage(currentPage=${(pageBean.pageNo)-1})}" th:if="${pageBean.pageNo != 1}">上一页</a>
<a th:each="i : ${#numbers.sequence(1,pageBean.totalPageNumber)}"
th:if="${pageBean.pageNo==i}">[[${i}]]</a>
<a th:each="i : ${#numbers.sequence(1,pageBean.totalPageNumber)}"
th:href="@{/toPage(currentPage=${i})}">[[${i}]]</a>
<a th:if="${pageBean.pageNo != pageBean.totalPageNumber}"
th:href="@{/toPage(currentPage=${pageBean.pageNo+1})}">下一页</a>
<a th:if="${pageBean.pageNo != pageBean.totalPageNumber}"
th:href="@{/toPage(currentPage=${pageBean.totalPageNumber})}">尾页</a>
转到 <input type="text" size="1" name="currentPage"/> 页
</td>
</tr>
</tbody>
</table>
</div>
</form>
</body>
</html>