springboot+jpa+tymeleaf实现分页功能

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介: springboot+jpa+tymeleaf实现分页功能

效果图

 

前端页面

 

 

环境介绍

jdk:1.8

数据库:mysql

前端:tymeleaf

后端:springboot+jpa

 

核心代码介绍

 

pox.xml

 

 

<dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-data-jpa</artifactId>        </dependency>                <dependency>            <groupId>mysql</groupId>            <artifactId>mysql-connector-java</artifactId>            <scope>runtime</scope>        </dependency>                <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-thymeleaf</artifactId>        </dependency>

 

 

mysql

 

 

DROP TABLE IF EXISTS `demo`;CREATE TABLE `demo` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `create_time` datetime DEFAULT NULL,  `des` longtext,  `modify_time` datetime DEFAULT NULL,  `name` varchar(50) DEFAULT NULL,  `remark` varchar(1024) DEFAULT NULL,  PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8;-- ------------------------------ Records of demo-- ----------------------------BEGIN;INSERT INTO `demo` VALUES (1, '2020-05-13 23:27:34', 'java是第一语言', '2020-05-13 23:28:14', 'java', '跟阿牛学java');INSERT INTO `demo` VALUES (2, '2020-05-13 23:27:34', 'javaee', '2020-05-13 23:28:14', '开发必备', '跟阿牛学java');INSERT INTO `demo` VALUES (3, '2020-05-13 23:27:34', 'javaee', '2020-05-13 23:28:14', '开发必备', '跟阿牛学java');INSERT INTO `demo` VALUES (6, '2020-05-13 23:27:34', 'javaee', '2020-05-13 23:28:14', '开发必备', '跟阿牛学java');INSERT INTO `demo` VALUES (10, '2020-05-13 23:27:34', 'javaee', '2020-05-13 23:28:14', '开发必备', '跟阿牛学java');INSERT INTO `demo` VALUES (11, '2020-05-13 23:27:34', 'javaee', '2020-05-13 23:28:14', '开发必备', '跟阿牛学java');INSERT INTO `demo` VALUES (13, '2020-05-13 23:27:34', 'javaee', '2020-05-13 23:28:14', '开发必备', '跟阿牛学java');COMMIT;

 

application.yml

 

 

server:  port: 9080spring:  servlet:    multipart:      max-file-size: 100MB      max-request-size: 100MB  datasource:    driverClassName: com.mysql.jdbc.Driver    url: jdbc:mysql://localhost/tests?characterEncoding=UTF8&useSSL=false    username: root    password: asdf678987  jpa:    database: MySQL    show-sql: true    hibernate:      ddl-auto: update    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect    open-in-view: false  thymeleaf:    cache: false    prefix: classpath:/templates/    suffix: .html    servlet:      content-type: text/html    mode: HTML5    encoding: UTF-8    resources:      chain:        strategy:          content:            enabled: true            paths: /**

 

Pager.java

 

 

package com.feige.tymeleaf.common;import java.io.Serializable;import java.util.ArrayList;import java.util.List;

 

public class Pager<T> implements Serializable {

 

  private static final long serialVersionUID = 4476276522269472300L;

 

  /**     * currentPage 当前页     */    private int currentPage = 1;    /**     * pageSize 每页大小     */    private int pageSize = 20;    /**     * pageTotal 总页数     */    private int pageTotal;    /**     * recordTotal 总条数     */    private int recordTotal = 0;    /**     * firstPage 第一页     */    private int firstPage = 1;

 

  /**     * content 每页的内容     */    private List<T> content;

 

  /**     * pager构造器     *     * @param content     */    public Pager(List<T> content, int currentPage, int pageSize) {        super();        this.content = content;        this.currentPage = currentPage;        this.pageSize = pageSize;        this.otherAttr();    }

 

  public Pager(List<T> content, int currentPage) {        super();        this.content = content;        this.currentPage = currentPage;        this.otherAttr();    }

 

  public Pager(List<T> content) {        super();        this.content = content;        this.otherAttr();    }

 

  /**     * pager获取分好页的数据记录     *     * @return     */    public List<T> getPageContent() {        if (this.content == null || this.content.size() < 1)            return null;

 

      List<T> pageContent = new ArrayList<T>();        //当前页的第一行为:(页码-1)x每页行数        int firstLine = (this.currentPage - 1) * this.pageSize;        //当前页的第最后行为:页码-x每页行数-1(如果最后一页为最大行数)        int lastLine = this.currentPage == this.pageTotal ? this.recordTotal : this.currentPage * this.pageSize;        for (int i = firstLine; i < lastLine; i++) {            pageContent.add(this.content.get(i));        }        return pageContent;    }

 

  // 以下set方式是需要赋值的

 

  /**     * 设置当前页 <br>     *     * @param currentPage     */    public void setCurrentPage(int currentPage) {        this.currentPage = currentPage;    }

 

  /**     * 设置每页大小,也可以不用赋值,默认大小为10条 <br>     *     * @param pageSize     */    public void setPageSize(int pageSize) {        this.pageSize = pageSize;    }

 

  /**     * 设置总条数,默认为0 <br>     *     * @param recordTotal     */    public void setRecordTotal(int recordTotal) {        this.recordTotal = recordTotal;        otherAttr();    }

 

  /**     * 设置分页内容 <br>     *     * @param content     */    public void setContent(List<T> content) {        this.content = content;    }

 

  /**     * 设置其他参数     */    public void otherAttr() {        if (this.content != null) {            // 总条数            this.recordTotal = this.content.size();            // 总页数            this.pageTotal = this.recordTotal % this.pageSize > 0 ? this.recordTotal / this.pageSize + 1 : this.recordTotal / this.pageSize;

 

          // 设置并调整当前页            if (this.currentPage < 1)                this.currentPage = 1;            else if (this.currentPage > this.pageTotal)                this.currentPage = this.pageTotal;        }    }

 

  /**     * @return the pageTotal     */    public int getPageTotal() {        return pageTotal;    }

 

  /**     * @param pageTotal the pageTotal to set     */    public void setPageTotal(int pageTotal) {        this.pageTotal = pageTotal;    }

 

 

  /**     * @return the firstPage     */    public int getFirstPage() {        return firstPage;    }

 

  /**     * @param firstPage the firstPage to set     */    public void setFirstPage(int firstPage) {        this.firstPage = firstPage;    }

 

 

  /**     * @return the serialversionuid     */    public static long getSerialversionuid() {        return serialVersionUID;    }

 

  /**     * @return the currentPage     */    public int getCurrentPage() {        return currentPage;    }

 

  /**     * @return the pageSize     */    public int getPageSize() {        return pageSize;    }

 

  /**     * @return the recordTotal     */    public int getRecordTotal() {        return recordTotal;    }

 

  /**     * @return the content     */    public List<T> getContent() {        return content;    }

 

  /* (non-Javadoc)     * @see java.lang.Object#toString()     */    @Override    public String toString() {        StringBuilder builder = new StringBuilder();        builder.append("Pager :{currentPage=");        builder.append(currentPage);        builder.append(", pageSize=");        builder.append(pageSize);        builder.append(", pageTotal=");        builder.append(pageTotal);        builder.append(", recordTotal=");        builder.append(recordTotal);        builder.append(", firstPage=");        builder.append(firstPage);        builder.append(", content=");        builder.append(content);        builder.append("}");        return builder.toString();    }}

 

TestController.java

 

 

 

 

package com.feige.tymeleaf.controller;import com.feige.tymeleaf.common.Pager;import com.feige.tymeleaf.common.Result;import com.feige.tymeleaf.common.StatusCode;import com.feige.tymeleaf.entity.Test;import com.feige.tymeleaf.service.TestService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.multipart.MultipartFile;import org.springframework.web.servlet.ModelAndView;

 

import javax.servlet.http.HttpServletRequest;import java.util.Map;

 

@RestController@RequestMapping("")public class TestController {

 

  @Autowired    TestService testServiceImpl;

 

  @RequestMapping(value="")    public ModelAndView test(@RequestParam Map<String,String> map) throws Exception {        ModelAndView mv = new ModelAndView("index");        Pager<Test> pager = testServiceImpl.findAll(map,2);        mv.addObject("listAll", pager.getPageContent());        mv.addObject("pageTotal", pager.getPageTotal());        mv.addObject("page", pager.getCurrentPage());        mv.addObject("Result","查询成功!");        return mv;    }}

 

 

index.html

 

 

<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head th:replace="common::head('测试')"><meta charset="UTF-8"></head><body><div class="table-responsive">    <table class="table table-striped" style="text-align: center;table-layout:fixed;" id="tableOne">        <thead>        <tr class="table_tr">            <th style="width:45px;text-align: center;">序号</th>            <th style="width:50px;text-align: center;">课程名称</th>            <th style="width:120px;text-align: center;">课程简介</th>            <th style="width:80px;text-align: center;">发布时间</th>            <th style="width:80px;text-align: center;">修改时间</th>            <th style="width:80px;text-align: center;">备注</th>        </tr>        </thead>        <tbody>        <tr th:each="tm,tmStat:${listAll}">            <td th:text="${tmStat.count}"></td>            <td class="yin" th:text="${tm.name}"></td>            <td class="yin" th:text="${tm.des}"></td>            <td class="yin dates" th:text="${tm.createTime}"></td>            <td class="yin dates" th:text="${tm.modifyTime}"></td>            <td class="yin dates" th:text="${tm.remark}"></td>        </tr>        </tbody>    </table>        <div th:replace="common::btn_pager"></div></div><div th:replace="common::scripts"></div><script language="javascript">    function changeColor(){        var color="#f00|容#0f0|#00f|#880|#808|#088|yellow|green|blue|gray";        color=color.split("|");        document.getElementById("blink").style.color=color[parseInt(Math.random() * color.length)];        document.getElementById("blink2").style.color=color[parseInt(Math.random() * color.length)];    }    setInterval("changeColor()",200);</script></body></html>


相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
3月前
|
SQL 数据库
若依框架---PageHelper分页(六)
若依框架---PageHelper分页(六)
38 0
|
18天前
|
Java
SpringBoot 集成Pagehelp分页
SpringBoot 集成Pagehelp分页
|
Java 数据库连接 测试技术
SpringBoot集成mybatis-plus及分页实现
SpringBoot集成mybatis-plus及分页实现
422 0
|
SQL XML 架构师
SpringBoot从小白到精通(十六)使用pagehelper实现分页查询功能
之前讲了Springboot整合Mybatis,然后介绍了如何自动生成pojo实体类、mapper类和对应的mapper.xml 文件,并实现最基本的增删改查功能。接下来要说一说Mybatis 的分页功能:使用Mybatis-PageHelper插件,实现分页功能。
SpringBoot从小白到精通(十六)使用pagehelper实现分页查询功能
|
3月前
|
SQL 安全 Java
若依框架---PageHelper分页(二)
若依框架---PageHelper分页(二)
51 0
|
3月前
|
SQL 缓存
若依框架---PageHelper分页(八)
若依框架---PageHelper分页(八)
19 0
|
4月前
|
XML Java 数据格式
springboot整合分页插件
springboot整合分页插件
27 5
|
5月前
|
XML Java 数据库连接
Spring集成【MyBatis】和【PageHelper分页插件】整合---详细介绍
Spring集成【MyBatis】和【PageHelper分页插件】整合---详细介绍
49 0
|
8月前
|
前端开发 Java 关系型数据库
SpringBoot-16-Spring-Data-Jpa实现分页排序
SpringBoot-16-Spring-Data-Jpa实现分页排序
70 0
|
SQL 前端开发 Java
Mybatis-PageHelper分页插件的使用与相关原理分析
今天使用了分页插件,并将其整合到SpringBoot中。各种遇到了个别问题,现在记录下。吃一垫长一智
196 0
Mybatis-PageHelper分页插件的使用与相关原理分析