SpringBoot结合Thymeleaf实现分页,很方便。

效果如下

后台代码

项目结构

1. 数据库Config

由于hibernate自动建表字符集为latin不能插入中文,故需要在application.properties中指定:spring.jpa.properties.hibernate.dialect=com.ikeguang.paging.config.MysqlConfig

MysqlConfig.java代码:

package com.ikeguang.paging.config;

import org.hibernate.dialect.MySQL5Dialect;
import org.springframework.stereotype.Component; /**
* @ Author: keguang
* @ Date: 2019/7/16 9:58
* @ version: v1.0.0
* @ description: 解决hibernate自动建表字符集为latin不能插入中文的问题。
*/
@Component
@SuppressWarnings("deprecation")
public class MysqlConfig extends MySQL5Dialect{ @Override
public String getTableTypeString() {
return "ENGINE=InnoDB DEFAULT CHARSET=utf8";
}
}

2. 实体类Model

package com.ikeguang.paging.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.io.Serializable; /**
* @ Author: keguang
* @ Date: 2019/6/24 20:18
* @ version: v1.0.0
* @ description:
*/
@Entity
public class User implements Serializable{
private static final long serialVersionUID = 1L; @Id
@GeneratedValue
private Long id;
@Column(nullable = false, unique = true)
private String userName;
@Column(nullable = false)
private String passWord;
@Column(nullable = false, unique = true)
private String email;
@Column(nullable = true, unique = true)
private String nickName;
@Column(nullable = false)
private String regTime; public User(){} public User(String userName, String passWord, String email, String nickName, String regTime) {
this.userName = userName;
this.passWord = passWord;
this.email = email;
this.nickName = nickName;
this.regTime = regTime;
}
// 省略了必须的getter、setter方法
}

3. Jpa操作数据库

UserRepository.java代码

package com.ikeguang.paging.repository;

import com.ikeguang.paging.model.User;
import org.springframework.data.jpa.repository.JpaRepository; /**
* @ Author: keguang
* @ Date: 2019/7/18 10:23
* @ version: v1.0.0
* @ description:
*/
public interface UserRepository extends JpaRepository<User, Long>{ User findById(long id); void deleteById(long id);
}

4. service层

UserService代码

package com.ikeguang.paging.service;

import com.ikeguang.paging.model.User;
import org.springframework.data.domain.Page; /**
* @ Author: keguang
* @ Date: 2019/7/18 10:26
* @ version: v1.0.0
* @ description:
*/
public interface UserService { Page<User> getUserList(int pageNum, int pageSize); User findUserById(long id); void save(User user); void edit(User user); void delete(long id);
}

service实现层

UserServiceImpl.java代码

package com.ikeguang.paging.service.impl;

import com.ikeguang.paging.model.User;
import com.ikeguang.paging.repository.UserRepository;
import com.ikeguang.paging.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service; /**
* @ Author: keguang
* @ Date: 2019/7/18 10:27
* @ version: v1.0.0
* @ description:
*/
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository; @Override
public Page<User> getUserList(int pageNum, int pageSize) { Sort sort = new Sort(Sort.Direction.DESC, "id");
Pageable pageable = PageRequest.of(pageNum, pageSize, sort);
Page<User> users = userRepository.findAll(pageable); return users;
} @Override
public User findUserById(long id) {
return userRepository.findById(id);
} @Override
public void save(User user) {
userRepository.save(user);
} @Override
public void edit(User user) {
userRepository.save(user);
} @Override
public void delete(long id) {
userRepository.deleteById(id);
}
}

5. Controller层

UserController .java代码

package com.ikeguang.paging.web;

import com.ikeguang.paging.model.User;
import com.ikeguang.paging.service.UserService;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import javax.annotation.Resource;
import java.util.Iterator; /**
* @ Author: keguang
* @ Date: 2019/7/18 10:29
* @ version: v1.0.0
* @ description:
*/
@Controller
public class UserController { @Resource
UserService userService; @RequestMapping("/")
public String index() {
return "redirect:/list";
} @RequestMapping("/list")
public String list(Model model, @RequestParam(value = "pageNum", defaultValue = "0") int pageNum, @RequestParam(value = "pageSize", defaultValue = "2") int pageSize) {
System.out.println("============================");
Page<User> users=userService.getUserList(pageNum, pageSize);
System.out.println("总页数" + users.getTotalPages());
System.out.println("当前页是:" + pageNum); System.out.println("分页数据:");
Iterator<User> u = users.iterator();
while (u.hasNext()){ System.out.println(u.next().toString());
} model.addAttribute("users", users); return "user/list";
} @RequestMapping("/toAdd")
public String toAdd() {
return "user/userAdd";
} @RequestMapping("/add")
public String add(User user) {
userService.save(user);
return "redirect:/list";
} @RequestMapping("/toEdit")
public String toEdit(Model model,Long id) {
User user=userService.findUserById(id);
model.addAttribute("user", user);
return "user/userEdit";
} @RequestMapping("/edit")
public String edit(User user) {
userService.edit(user);
return "redirect:/list";
} @RequestMapping("/delete")
public String delete(Long id) {
userService.delete(id);
return "redirect:/list";
}
}

application.properties配置文件

主要配制了mysql数据源,数据库驱动com.mysql.cj.jdbc.Driver,对于mysql-connector-java用的6.0以上的,如果用com.mysql.jdbc.Driver,就会报错。

spring.datasource.url=jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # 表不存在则新建表
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=com.ikeguang.paging.config.MysqlConfig
spring.jpa.show-sql= true spring.thymeleaf.cache=false

模板文件

这里用了bootstrap.css里面的样式。这里主要展示一下分页代码,前面的table主要装一个PageableN条数据,接着是一个add添加数据的按钮,最下面就是分页部分,主要有5部分:首页,上一页,中间页,下一页,尾页

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>userList</title>
<link rel="stylesheet" th:href="@{/css/bootstrap.css}"></link> </head>
<body class="container">
<br/>
<h1>用户列表</h1>
<br/><br/>
<div class="with:80%">
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>userName</th>
<th>passWord</th>
<th>email</th>
<th>nickName</th>
<th>regTime</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr th:each="user : ${users}">
<th scope="row" th:text="${userStat.index + 1}">1</th>
<td th:text="${user.userName}">neo</td>
<td th:text="${user.passWord}">Otto</td>
<td th:text="${user.email}">6</td>
<td th:text="${user.nickName}">6</td>
<td th:text="${user.regTime}">6</td>
<td><a th:href="@{/toEdit(id=${user.id})}">edit</a></td>
<td><a th:href="@{/delete(id=${user.id})}">delete</a></td>
</tr>
</tbody>
</table> </div>
<div class="form-group">
<div class="col-sm-2 control-label">
<a href="/toAdd" th:href="@{/toAdd}" class="btn btn-info">add</a>
</div>
</div> <div class="modal-footer no-margin-top">
<ul class="pagination pull-right no-margin"> <!-- 首页 -->
<li>
<a th:href="'/list?pageNum=0'">首页</a>
</li> <!-- 上一页 -->
<li th:if="${users.hasPrevious()}">
<a th:href="'/list?pageNum=' + ${users.previousPageable().getPageNumber()}" th:text="上一页"></a>
</li> <!-- 中间页 -->
<li th:each="pageNum:${#numbers.sequence(0, users.getTotalPages() - 1)}">
<a th:href="'/list?pageNum=' + ${pageNum}" th:text="${pageNum + 1}" th:if="${pageNum ne users.pageable.getPageNumber()}"></a>
<a th:href="'/list?pageNum=' + ${pageNum}" th:text="${pageNum + 1}" th:if="${pageNum eq users.pageable.getPageNumber()}" th:style="'font-weight:bold;background: #6faed9;'"></a>
</li> <!-- 下一页 -->
<li th:if="${users.hasNext()}">
<a th:href="'/list?pageNum=' + ${users.nextPageable().getPageNumber()}" th:text="下一页"></a>
</li> <!-- 尾页 -->
<li>
<a th:href="'/list?pageNum=' + ${users.getTotalPages() - 1}">尾页</a>
</li> </ul>
</div> </body>
</html>

代码Github

代码的Github地址:代码地址

SpringBoot + thymeleaf 实现分页的更多相关文章

  1. java+springBoot+Thymeleaf+vue分页组件的定义

    导读 本篇着重介绍java开发环境下,如何写一个vue分页组件,使用到的技术点有java.springBoot.Thymeleaf等: 分页效果图 名称为vuepagerbasic的分页组件,只包含上 ...

  2. springboot+thymeleaf+pageHelper带条件分页查询

    html层 <div> <a class="num"><b th:text="'共 '+ ${result.resultMap['pages ...

  3. org.springframework.expression.spel.SpelEvaluationException: EL1004E: Method call: Method service() cannot be found on com.my.blog.springboot.thymeleaf.util.MethodTest type

    前言 本文中提到的解决方案,源码地址在:springboot-thymeleaf,希望可以帮你解决问题. 至于为什么已经写了一篇文章thymeleaf模板引擎调用java类中的方法,又多此一举的单独整 ...

  4. springboot+thymeleaf简单使用

    关于springboot想必很多人都在使用,由于公司项目一直使用的是SpringMVC,所以自己抽空体验了一下springboot的简单使用. 环境搭建 springbooot的环境搭建可以说很灵活, ...

  5. SpringBoot thymeleaf使用方法,thymeleaf模板迭代

    SpringBoot thymeleaf使用方法,thymeleaf模板迭代 SpringBoot thymeleaf 循环List.Map ============================= ...

  6. SpringBoot thymeleaf模板页面没提示,SpringBoot thymeleaf模板插件安装

    SpringBoot thymeleaf模板插件安装 SpringBoot thymeleaf模板Html页面没提示 SpringBoot  thymeleaf模板页面没提示 SpringBoot t ...

  7. SpringBoot thymeleaf模板版本,thymeleaf模板更换版本

    SpringBoot thymeleaf模板版本 thymeleaf模板更换版本 修改thymeleaf模板版本 ================================ ©Copyright ...

  8. Springboot+Thymeleaf框架的button错误

    ---恢复内容开始--- 在做公司项目时,遇到了一个Springboot+Thymeleaf框架问题: 使用框架写网站时,没有标明type类型的button默认成了‘submit’类型,每次点击按钮都 ...

  9. SpringBoot+Thymeleaf+iView

    SpringBoot+Thymeleaf参考: https://www.cnblogs.com/kibana/p/10236187.html 1.Controller: package cn.mmwe ...

随机推荐

  1. 编辑器 --- Visual Studio Code 英文界面转换成中文(简体)

    打开编辑器 同时按下Ctrl+Shift+P打开命令面板: 之后输入"config"筛选可用命令表,最后选择配置语言命令进行选择或安装插件

  2. ao的mobile解决方案

    http://aicdg.com/ue4-msaa-depth/ http://aicdg.com/vulkan-mass-shader-resolve/ ao两篇paper 分bake和realti ...

  3. sql server 安装

    第一次安装sql server是2016版本,因为[win7-64版系统配置比较低],所以不成功. 第二次安装2012版,在[数据库引擎配置]的时候,选择的是[添加当前用户],以及后续需要添加用户的时 ...

  4. windows下常用cmd命令

    CMD命令:开始->运行->键入cmd或command(在命令行里可以看到系统版本.文件系统版本)1. appwiz.cpl:程序和功能 2. calc:启动计算器 3. certmgr. ...

  5. HDU 6102 - GCDispower | 2017 Multi-University Training Contest 6

    个人感觉题解的复杂度很玄,参不透,有没有大佬讲解一下- - /* HDU 6102 - GCDispower [ 数论,树状数组] | 2017 Multi-University Training C ...

  6. Ubuntu操作及Linux基础知识

    part 1: Ubuntu操作基础 1.调整字体的大小 调大:crtl+shift+“+”  调小:crtl+“-” 2.不要把虚拟机全屏的时候截屏,要不然会认为是Linux系统截屏而非Window ...

  7. 初入SG-UAP

    初入SG-UAP SpriderMan 关注 2019.06.19 14:10 字数 1130 阅读 10评论 0喜欢 0 初次接触SG-UAP,将自己的见解以文字形式记录下来,希望能对初入的伙伴们有 ...

  8. HDOJ 4858 项目管理 ( 只是有点 莫队的分块思想在里面而已啦 )

    题目: 链接:http://acm.hdu.edu.cn/showproblem.php?pid=4858 题意: 我们建造了一个大项目!这个项目有n个节点,用很多边连接起来,并且这个项目是连通的! ...

  9. vim.rc配置(deepin)

    set nocompatible " be iMproved, requiredfiletype off " required " set the runtime pat ...

  10. 【集训队作业2018】count

    CSP后第一发Blog. 这道题没有一下子过掉,开始还推出了错的结论.在错误的生成函数里绕了好久-- 很显然的转笛卡尔树,一个笛卡尔树对应一种序列.只要考虑一个笛卡尔树是否合法. 贪心地填数发现,从根 ...