SpringBoot整合Thymeleaf实现增删改查分页

SpringBoot整合Thymeleaf实现增删改查分页

哔哩哔哩链接:https://www.bilibili.com/video/BV1wy4y1J7Zf?p=1

效果展示

我们输入 http://localhost:8080/ 进入主界面,

SpringBoot整合Thymeleaf实现增删改查分页_第1张图片

可以输入用户名进行搜索、可以新增、编辑、删除、修改

项目目录

我们的项目目录结构如下:

SpringBoot整合Thymeleaf实现增删改查分页_第2张图片

1.创建SpringBoot项目

此处我们使用ideal作为演示,我们新建一个springboot项目,

SpringBoot整合Thymeleaf实现增删改查分页_第3张图片

配置项目信息之后,点击next

SpringBoot整合Thymeleaf实现增删改查分页_第4张图片

选择依赖,简单选择即可

SpringBoot整合Thymeleaf实现增删改查分页_第5张图片

命名项目和位置,之后点击finish

SpringBoot整合Thymeleaf实现增删改查分页_第6张图片

2.引入依赖

我们需要引入项目的更多依赖,打开项目的pom.xml文件引入依赖,具体代码如下:


<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.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.2.5.RELEASEversion>
        <relativePath/> 
    parent>
    <groupId>com.examplegroupId>
    <artifactId>demoartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>demoname>
    <description>Demo project for Spring Bootdescription>
    <properties>
        <java.version>1.8java.version>
    properties>
    <dependencies>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-thymeleafartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>2.1.3version>
        dependency>
        
        <dependency>
            <groupId>com.github.pagehelpergroupId>
            <artifactId>pagehelper-spring-boot-starterartifactId>
            <version>1.3.0version>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.2.4version>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>
        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombokgroupId>
                            <artifactId>lombokartifactId>
                        exclude>
                    excludes>
                configuration>
            plugin>
        plugins>
    build>

project>

3.新建数据库

我们数据库名称为mybatis,里面有一张表,名为 user ,如图:

SpringBoot整合Thymeleaf实现增删改查分页_第7张图片

4.新建实体类

我们新建包pojo,在其包下新建 User.java实体类,以及查询类UserQuery.java ,由于我们在pom.xml中引入了lombok依赖,可以省略getter和setter等方法。

SpringBoot整合Thymeleaf实现增删改查分页_第8张图片

Lombok插件安装

我们可以在ideal中安装Lombok插件,让我们的ideal可以支持lombok,具体步骤如下:

点击 File 下的 Settings

SpringBoot整合Thymeleaf实现增删改查分页_第9张图片

之后在Settings面板下点击 Plugins

SpringBoot整合Thymeleaf实现增删改查分页_第10张图片

安装好lombok插件后,我们的具体代码如下:

User.java

package com.example.demo.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/*
*
* 加了@Data注解的类,编译后会自动给我们加上下列方法:
    所有属性的get和set方法
    toString 方法
    hashCode方法
    equals方法
*
* @AllArgsConstructor :有参构造方法
* @NoArgsConstructor :无参构造方法
* */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
    private Integer id;
    private String name;
    private String pwd;
    private String userIntroduce;
}

我们可以查看lombok是否帮助我们添加了对应的方法:

SpringBoot整合Thymeleaf实现增删改查分页_第11张图片

UserQuery.java

package com.example.demo.pojo.query;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserQuery {
    private Integer pageNum = 1;   // 当前的页码
    private Integer pageSize  = 2;   //每一页所显示的数量
    private String name;    // 根据用户查询
}

5.新建dao

我们新建dao包,在其包下新建接口并命名为 UserDao.java ,具体代码如下:

UserDao.java

package com.example.demo.dao;


import com.example.demo.pojo.User;
import com.example.demo.pojo.query.UserQuery;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;


import java.util.List;

@Mapper  // 告诉springboot这是一个mybatis的mapepr类
@Repository   // 将userdao交由spring容器管理
public interface UserDao {
    // 查询所有用户
    public List<User> listUser();
    
    // 根据id查询用户
    public User queryUserById(Integer id);
    
    // 根据用户名来查询用户  并分页展示
    public List<User> listUserByName(UserQuery userQuery);

    //根据id删除用户
    public int deleteUserById(Integer id);

    // 修改用户
    public int updateUser(User user);

    // 新增用户
    public int addUser(User user);

    // 判断用户名是否存在
    public int selectUserByName(String name);
}

扩展

如果我们有多个dao接口,我们可以不用在每个接口上都添加 @Mapper 注解,直接在项目启动类上添加 @MapperScan(dao包的路径)

SpringBoot整合Thymeleaf实现增删改查分页_第12张图片

6.新建Mapper

我们在项目resources资源目录下新建一个 mapper 包,并在其包下新建 UserMapper.xml 文件,编写UserDao.java接口对应的sql语句,具体代码如下:

UserMapper.xml


DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.dao.UserDao">

    <resultMap type="com.example.demo.pojo.User" id="UserDaoResult">
        <id     property="id"   column="id"   />
        <result property="name"   column="name"   />
        <result property="pwd"  column="pwd"  />
        <result property="userIntroduce"  column="user_introduce"  />
    resultMap>

    <sql id="selectUserVo">
        select id, name, pwd, user_introduce from user
    sql>

    <select id="listUser" resultType="User">
        select *
        from user;
    select>

    <select id="listUserByName" parameterType="com.example.demo.pojo.query.UserQuery" resultType="User">
        select *
        from user
        <where>
            <if test="name != null and name != ''">
                and `name` like concat('%',#{name},'%')
            if>
        where>
    select>

    <delete id="deleteUserById" parameterType="int">
        delete from user where id=#{id}
    delete>

    <select id="queryUserById" parameterType="int" resultMap="UserDaoResult">
        <include refid="selectUserVo" />
        where  id=#{id}
    select>


    <select id="selectUserByName" parameterType="String" resultType="Integer">
        select count(id) from user
        where  name=#{name}
    select>


    <update id="updateUser" parameterType="User">
        update user
        set name = #{name},pwd = #{pwd}
        where id = #{id}
    update>

    <insert id="addUser" parameterType="User">
        insert into user(name, pwd) values (#{name},#{pwd})
    insert>
mapper>

7.application.yml配置

注意:ideal创建的springboot项目的配置文件默认是properties格式的,这里我们将其后缀更改为yml,具体代码如下:

server:
  port: 8080

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis:
  type-aliases-package: com.example.demo.pojo   # 实体类位置
  mapper-locations: classpath:/mybatis/*.xml   #  mapper位置
  configuration:
    map-underscore-to-camel-case: true  # 驼峰转换

logging:
  file:
    name: log/log.log   # 输出日志文件目录(在项目根目录)
  level:
    root: info
    wuhobin: debug

8.新建service

新建接口 UserService.java 以及他的实现类 UserServiceImpl.java ,具体代码如下:

UserService.java

package com.example.demo.service;

import com.example.demo.pojo.User;
import com.example.demo.pojo.query.UserQuery;
import com.github.pagehelper.PageInfo;


import java.util.List;

public interface UserService {
    // 查询所有用户
    public List<User> listUser();
    
    // 根据用户名来查询用户  并分页展示
    public PageInfo<User> listUserByName(UserQuery userQuery);

    //根据id删除用户
    public boolean deleteUserById(Integer id);

    // 根据id查询用户
    public User queryUserById(Integer id);

    // 修改用户
    public boolean updateUser(User user);

    // 新增用户
    public boolean addUser(User user);

    public int selectUserByName(String name);
}

UserServiceImpl.java

package com.example.demo.service.Impl;

import com.example.demo.dao.UserDao;
import com.example.demo.pojo.User;
import com.example.demo.pojo.query.UserQuery;
import com.example.demo.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.List;

@Service   //  交由spring容齐管理
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    public List<User> listUser() {
        return userDao.listUser();
    }

    @Override
    public PageInfo<User> listUserByName(UserQuery userQuery) {
        PageHelper.startPage(userQuery.getPageNum(),userQuery.getPageSize());
        return new PageInfo<User>(userDao.listUserByName(userQuery));
    }

    @Override
    public boolean deleteUserById(Integer id) {
        int i = userDao.deleteUserById(id);
        if(i > 0){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public User queryUserById(Integer id) {
        return userDao.queryUserById(id);
    }

    @Override
    public boolean updateUser(User user) {
        int i = userDao.updateUser(user);
        if(i > 0){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public boolean addUser(User user) {
        return userDao.addUser(user) > 0 ? true : false ;
    }

    @Override
    public int selectUserByName(String name) {
        return userDao.selectUserByName(name);
    }
}

9.新建html文件

我们在resources的templates下新建 index.html 和 editUser.html 文件,具体代码如下:

我们前端使用的ui框架为 semantic-ui ,文档地址: https://semantic-ui.com/introduction/getting-started.html

index.html

DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/semantic.min.css">
head>
<body>
<div class="ui container">
    <div class="ui attached segment">
        <form th:action="@{/}" method="post" style="display: inline-block !important;">
            <input type="text" name="name" placeholder="输入用户名查找">
            <input type="submit" value="搜索">
        form>
        <a th:href="@{/update}" class="ui button mini teal" style="margin-left: 30px !important;">新增a>
    div>
    <table class="ui celled attached table" style="margin-top: 40px !important;">
        <thead>
        <tr><th>idth>
            <th>姓名th>
            <th>密码th>
            <th>操作th>
        tr>thead>
        <tbody>
        <tr th:each="user : ${page.list}">
            <td th:text="${user.id}">Jamestd>
            <td th:text="${user.name}">24td>
            <td th:text="${user.pwd}">Engineertd>
            <td>
                <a th:href="@{/edit/{id}(id=${user.id})}" class="ui button mini pink">编辑a>
                <a th:href="@{/delete/{id}(id=${user.id})}" class="ui button mini teal">删除a>
            td>
        tr>
        tbody>
    table>
    <div class="ui attached segment" >
        <table class="m-mobile-wide" width="425px">
            <tbody>
            <tr align="center">
                <td>
                    <a th:href="@{/(pageNum=${page.pageNum}-1)}"  class="ui button basic mini" th:unless="${page.isFirstPage}">上一页a>
                td>
                <td><h8 th:text="${page.pageNum}">2h8>
                    页/共
                    <h8 th:text="${page.pages}">4h8>
                    页
                    共
                    <h8 th:text="${page.total}">29h8>td>
                <td>
                    <form name="pageForm" th:action="@{/}" method="get">
                        <div class="ui mini input ">
                            <input type="text" class="m-bg" name="pageNum" placeholder="页码" style="width: 50px!important; height: 27.76px!important;" required>
                            <button type="submit" style="font-size: 11px!important;width: 30px!important; height: 0px!important; border: none;margin: 5px;padding: 0;" class="button mini">
                                跳转
                            button>
                        div>
                    form>
                td>
                <td>  td>
                <td  style="float: right">
                    <a th:href="@{/(pageNum=${page.pageNum}+1)}" class="ui button basic mini " style="float: right;" th:unless="${page.isLastPage}">下一页a>
                td>
            tr>
            tbody>
        table>
    div>
    <div class="ui success  message" th:unless="${#strings.isEmpty(message)}">
        <i class="close icon">i>
        <div class="header">提示:div>
        <p th:text="${message}">p>
    div>
div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js">script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/semantic.min.js">script>
<script>
    $(".message .close").on('click',function () {
        $(this).closest(".message")
            .transition("fade");
    })
script>
body>
html>

editUser.html

DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>修改用户title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/semantic.min.css">
head>
<body>
<div class="ui container">
    <form class="ui form" th:action="@{/edit}" method="post" th:object="${user}">
        <input type="hidden" th:value="*{id}" name="id">
        <div class="field">
            <label>用户名label>
            <input type="text" name="name" placeholder="请输入用户名" required th:value="*{name}">
        div>
        <div class="field">
            <label>密码label>
            <input type="text" name="pwd" placeholder="请输入密码" required th:value="*{pwd}">
        div>
        <button class="ui button" type="submit">提交button>
    form>

    <div class="ui success  message" th:unless="${#strings.isEmpty(message)}">
        <i class="close icon">i>
        <div class="header">提示:div>
        <p th:text="${message}">p>
    div>
div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js">script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/semantic.min.js">script>
<script>
    $(".message .close").on('click',function () {
        $(this).closest(".message")
            .transition("fade");
    })
script>
body>
html>

10.新建controller

我们新建 UserController.java ,具体代码如下:

package com.example.demo.controller;


import com.example.demo.pojo.User;
import com.example.demo.pojo.query.UserQuery;
import com.example.demo.service.UserService;
import com.github.pagehelper.PageInfo;
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 org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;


@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/")
    public String index(Model model, UserQuery userQuery) {
        PageInfo<User> userPageInfo = userService.listUserByName(userQuery);
        model.addAttribute("page", userPageInfo);
        return "index";
    }

    @PostMapping("/")
    public String listUserByName(Model model, UserQuery userQuery) {
        PageInfo<User> userPageInfo = userService.listUserByName(userQuery);
        model.addAttribute("page", userPageInfo);
        return "index";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id") Integer id, RedirectAttributes attributes) {
        boolean b = userService.deleteUserById(id);
        if (b) {
            attributes.addFlashAttribute("message", "删除用户成功");
            return "redirect:/";
        } else {
            attributes.addFlashAttribute("message", "删除用户失败");
            return "redirect:/";
        }
    }


    @GetMapping("/edit/{id}")
    public String toEdit(@PathVariable Integer id, Model model) {
        model.addAttribute("user", userService.queryUserById(id));
        return "editUser";
    }


    @PostMapping("/edit")
    public String edit(User user, RedirectAttributes attributes) {
        int i = userService.selectUserByName(user.getName());
        /* 根据id的是否为null判断新增还是修改操作,null为新增,不为null为修改 */
        Integer id = user.getId();
        /* 修改用户 */
        if (id != null) {
            /* 用户名不存在 */
            if (i == 0) {
                boolean b = userService.updateUser(user);
                if (b) {
                    attributes.addFlashAttribute("message", " 更新用户成功");
                    return "redirect:/";
                } else {
                    attributes.addFlashAttribute("message", "更新用户失败");
                    return "redirect:/";
                }
            } else {
                attributes.addFlashAttribute("message", "该用户名已存在");
                return "redirect:/edit/" + user.getId();
            }
        // 新增用户
        } else {
            if (i == 0) {
                boolean b = userService.addUser(user);
                if (b) {
                    attributes.addFlashAttribute("message", " 新增用户成功");
                    return "redirect:/";
                } else {
                    attributes.addFlashAttribute("message", "新增用户失败");
                    return "redirect:/";
                }
            } else {
                attributes.addFlashAttribute("message", "该用户名已存在");
                return "redirect:/";
            }
        }
    }

    /* 新增操作 */
    @GetMapping("/update")
    public String toUpdate(Model model) {
        User user = new User();
        model.addAttribute("user", user);
        return "editUser";
    }
}

11.启动项目

SpringBoot整合Thymeleaf实现增删改查分页_第13张图片

项目演示

我们输入 http://localhost:8080/ 进入主界面,

SpringBoot整合Thymeleaf实现增删改查分页_第14张图片

可以输入用户名进行查找、可以新增、编辑、删除、修改,此处我们介绍分页的代码和操作消息提示的代码

分页的代码

显示当前页数、总页数和总条数,当前是第一页时不显示“上一页”,当前是最后一页时不显示“下一页”,可以输入具体的页面进行跳转

<div class="ui attached segment" >
            <table class="m-mobile-wide" width="425px">
                <tbody>
                <tr align="center">
                    <td>
                        <a th:href="@{/(pageNum=${page.pageNum-1})}"  class="ui button basic mini" th:unless="${page.isFirstPage}">上一页a>
                    td>
                    <td><h8 th:text="${page.pageNum}">2h8>
                        页/共
                        <h8 th:text="${page.pages}">4h8>
                        页
                        共
                        <h8 th:text="${page.total}">29h8>td>
                    <td>
                        <form name="pageForm" th:action="@{/}" method="get">
                            <div class="ui mini input ">
                                <input type="text" class="m-bg" name="pageNum" placeholder="页码" style="width: 50px!important; height: 27.76px!important;" required>
                                <button type="submit" style="font-size: 11px!important;width: 30px!important; height: 0px!important; border: none;margin: 5px;padding: 0;" class="button mini">
                                    跳转
                                button>
                            div>
                        form>
                    td>
                    <td>  td>
                    <td  style="float: right">
                        <a th:href="@{/(pageNum=${page.pageNum+1})}" class="ui button basic mini " style="float: right;" th:unless="${page.isLastPage}">下一页a>
                    td>
                tr>
                tbody>
            table>
    div>

操作消息提示

<div class="ui success  message m-bg" th:unless="${#strings.isEmpty(message)}">
    <i class="close icon">i>
    <div class="header">提示:div>
    <p th:text="${message}">p>
div>

$(".message .close").on('click',function () {
    $(this).closest(".message")
        .transition("fade");
})

如我们新增用户成功时,

SpringBoot整合Thymeleaf实现增删改查分页_第15张图片

常用注解

@Mapper
// 使用这个注解表示这是一个mybatis的mapper类
@Component
// 泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。    
@Repository
// 用于dao层 用于标注数据访问组件,即dao层 
@Service
// 用于标注业务层组件 
@Controller
// 用于标注控制层组件(如struts中的action) 
// 以上四个注解的作用都是将相应的类注入到spring容器中

源码获取

至此,我们的SpringBoot整合Thymeleaf实现增删改查分页就讲解完成了。源码和数据库文件可以通过关注我的微信公众号 我爱学习呀嘻嘻 ,回复关键字thymeleaf集成进行获取哦。

image-20211108230322493

你可能感兴趣的:(spring,boot,mybatis)