SpringBoot + Thymeleaf 實現單表的增刪改查

前言

  • 前端:ThymeleafbootstrapjQuery
  • 後端:SpringBootMybatis
  • 數據庫:MySQL
  • 工具:IDEA
  • 環境:JDK1.8Maven

一、創建表,添加數據

1、創建數據庫:CREATE table users (id int(20) auto_increment primary key,name VARCHAR(20) not null,age int(20) not null,sex varchar(20) not null,address varchar(30) not null);

2、插入數據:insert into users (name,age,sex,address) values("詹姆斯",36,"男","洛杉磯湖人");

3、插入幾條數據後如下圖:
在這裏插入圖片描述

二、IDEA創建SpringBoot項目

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

1、在 pom.xml 中配置項目依賴

<?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.2.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>cn.lemon</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <!--指定字符集-->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <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>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2、啓動類 DemoApplication.java

package cn.lemon.demo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("cn.lemon.demo.dao")
public class DemoApplication {

  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }
}

3、配置文件application.properties

## 端口
server.port=8083

##數據源配置
spring.datasource.url=jdbc:mysql://localhost:3306/db_users
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

##MyBatis配置
mybatis.mapper-locations=classpath*:mybatis/*.xml
mybatis.type-aliases-package=cn.lemon.demo.domain

#thymelea模板配置
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html

#熱部署文件,頁面不產生緩存,及時更新
#關閉模板緩存
spring.thymeleaf.cache=false
#spring.resources.chain.strategy.content.enabled=true
#spring.resources.chain.strategy.content.paths=/**

三、後端代碼編寫

1、創建實體類 User.java 映射數據庫user表

package cn.lemon.demo.domain;

public class User {

  private String address;
  private int age;
  private Integer id;
  private String name;
  private String sex;

  public String getAddress() {
    return address;
  }

  public void setAddress(String address) {
    this.address = address;
  }

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }

  public Integer getId() {
    return id;
  }

  public void setId(Integer id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getSex() {
    return sex;
  }

  public void setSex(String sex) {
    this.sex = sex;
  }
}

2、創建數據庫訪問層 IUserDao.java 接口、IUserDao.xml 映射文件,對數據庫表的增刪改查

package cn.lemon.demo.dao;

import cn.lemon.demo.domain.User;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface IUserDao {

  public int add(User user);


  public int delete(Integer id);


  public List<User> findAll();


  public User findById(Integer id);


  public List<User> findByName(String name);


  public int update(User user);


}
<?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">
<mapper namespace="cn.lemon.demo.dao.IUserDao">

    <insert id="add" parameterType="user">
        INSERT INTO
        `user`(`name`,`age`,`sex`,`address`)
        VALUES
        (#{name},#{age},#{sex},#{address})
    </insert>

    <delete id="delete">
        delete from user where id = #{id}
    </delete>

    <select id="findAll" resultType="user">
        select * from user
    </select>

    <select id="findById" resultType="user">
        select * from user where id = #{id}
    </select>

    <select id="findByName" resultType="user">
        select * from user where name like concat(concat('%',#{name}),'%')
    </select>

    <update id="update">
        update user set name=#{name},age=#{age},sex=#{sex},address=#{address} where user.id=#{id}
    </update>
</mapper>

3、創建業務邏輯層 IUserService.java接口以及UserServiceImpl.java實現類

package cn.lemon.demo.service;

import cn.lemon.demo.domain.User;

import java.util.List;

public interface IUserService {

  public int add(User user);


  public int delete(Integer id);


  public List<User> findAll();


  public User findById(Integer id);


  public List<User> findByName(String name);


  public int update(User user);


}
package cn.lemon.demo.service.impl;

import cn.lemon.demo.dao.IUserDao;
import cn.lemon.demo.domain.User;
import cn.lemon.demo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements IUserService {

  @Autowired
  private IUserDao iUserDao;

  @Override
  public int add(User user) {
    return iUserDao.add(user);
  }


  @Override
  public int delete(Integer id) {
    return iUserDao.delete(id);
  }


  @Override
  public List<User> findAll() {
    return iUserDao.findAll();
  }


  @Override
  public User findById(Integer id) {
    return iUserDao.findById(id);
  }


  @Override
  public List<User> findByName(String name) {
    return iUserDao.findByName(name);
  }


  @Override
  public int update(User user) {
    return iUserDao.update(user);
  }


}

4、創建控制層 UserController.java

package cn.lemon.demo.web.controller;

import cn.lemon.demo.domain.User;
import cn.lemon.demo.service.impl.UserServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
  @Resource
  private UserServiceImpl userService;

  @GetMapping("/delete/{id}")
  public String delete(@PathVariable Integer id) {
    userService.delete(id);
    return "redirect:/user/userList";
  }


  @RequestMapping("/insertPage")
  public String insertPage() {
    return "insertPage";
  }


  @RequestMapping("/insert")
  public String insert(User user) {
    userService.add(user);
    return "redirect:/user/userList";
  }


  @RequestMapping("/select/{id}")
  @ResponseBody
  public String select(@PathVariable int id) {
    return userService.findById(id).toString();
  }


  @GetMapping("/updatePage/{id}")
  public String updatePage(Model model, @PathVariable int id) {
    User user = userService.findById(id);
    model.addAttribute("user", user);
    return "updatePage";
  }


  @PostMapping("/update")
  public String update(User user) {
    userService.update(user);
    return "redirect:/user/userList";
  }


  @RequestMapping("/userList")
  public String userList(Model model) {
    List<User> users = userService.findAll();
    model.addAttribute("users", users);
    return "userList";
  }

  @RequestMapping("/find")
  public String userFind(Model model,String name) {
    List<User> users = userService.findByName(name);
    model.addAttribute("users", users);
    return "userList";
  }

}

5、服務層測試 UserServiceImplTest.java(Ctrl + Shift + T)

package cn.lemon.demo.service.impl;

import cn.lemon.demo.domain.User;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

import static org.junit.jupiter.api.Assertions.*;

@SpringBootTest
@RunWith(SpringRunner.class)
class UserServiceImplTest {

  @Autowired
private UserServiceImpl userService;

  @Test
  void add() {
    User user = new User();
    user.setName("萊昂納德");
    user.setAge(30);
    user.setSex("男");
    user.setAddress("洛杉磯快船");
    userService.add(user);
  }


  @Test
  void delete() {
    userService.delete(10);
  }


  @Test
  void findAll() {
    List<User> userList = userService.findAll();
    for (User user : userList) {
      System.out.println(user.getName());
    }
  }


  @Test
  void findById() {
    User user = userService.findById(1);
    System.out.println(user.getName() + user.getAddress());
  }


  @Test
  void findByName() {
    List<User> userList = userService.findByName("詹");
    for (User user : userList) {
      System.out.println(user.getName() + user.getAddress());
    }
  }


  @Test
  void update() {
    User user = new User();
    user.setId(14);
    user.setName("隆多");
    user.setAge(35);
    user.setSex("男");
    user.setAddress("洛杉磯湖人");
    userService.update(user);
  }


}

四、前端頁面編寫

1、導入 CSS、JavaScript

  • 路徑:demo\src\main\resources\static\css\bootstrap.css
  • 路徑:demo\src\main\resources\static\js\bootstrap.min.js
  • 路徑:demo\src\main\resources\static\js\jquery.min.js
注意:

SpringBoot項目創建後,resources下默認有兩個文件夾static和template.一般static存放靜態資源,template存放動態資源

2、在\resources\template創建userList.html列表頁面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <title>用戶列表</title>
  <link rel="stylesheet" type="text/css" th:href="@{/css/bootstrap.css}"/>
  <script type="text/javascript" th:src="@{/js/jquery.min.js}"></script>
  <script type="text/javascript" th:src="@{/js/bootstrap.min.js}"></script>
</head>

<style>
  a {
    color: #fff;
  }
</style>

<body>
<h2 style="text-align: center">用戶列表</h2>
<div style="text-align: center;">
  <div class="btn-group">
    <form th:action="@{'/user/find'}">
      <input name="name" class="form-control" type="text" placeholder="請輸入用戶名..." style="float: left; width:70%;"/>
      <input class="btn btn-primary form-control" type="submit" value="查詢" style="width: 28%"/>
    </form>
  </div>&nbsp&nbsp
  <div class="btn-group">
    <button class="btn btn-primary form-control btn-sm"><a th:href="@{'/user/insertPage'}">添加用戶</a></button>
  </div>
</div>
<table class="table table-striped table-bordered table-hover text-center">
  <thead>
  <tr style="text-align:center">
    <th>編號</th>
    <th>姓名</th>
    <th>年齡</th>
    <th>性別</th>
    <th>地址</th>
    <th>操作</th>
  </tr>
  </thead>
  <tbody>
  <tr th:each="users:${users}">
    <td th:text="${users.id}"></td>
    <td th:text="${users.name}"></td>
    <td th:text="${users.age}"></td>
    <td th:text="${users.sex}"></td>
    <td th:text="${users.address}"></td>
    <td>
      <a class="btn btn-primary" th:href="@{'/user/updatePage/'+${users.id}}">修改</a>
      <a class="btn btn-danger" th:href="@{'/user/delete/'+${users.id}}">刪除</a>
    </td>
  </tr>
  </tbody>
</table>
</body>
</html>

3、在\resources\template創建updatePage.html修改頁面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>修改用戶</title>
  <link rel="stylesheet" type="text/css" th:href="@{/css/bootstrap.css}"/>
</head>
<body>

<div style="width:800px;height:100%;margin-left:270px;">
  <form action="/user/update" method="post">
    編號:<input class="form-control" name="id" type="text" th:value="${user.id}" readonly="readonly"><br>
    姓名:<input class="form-control" type="text" th:value="${user.name}" name="name"><br>
    年齡:<input class="form-control" type="text" th:value="${user.age}" name="age"><br>
    性別:<input class="form-control" type="text" th:value="${user.sex}" name="sex"><br>
    地址:<input class="form-control" type="text" th:value="${user.address}" name="address"><br>
    <button class="btn btn-primary btn-lg btn-block" type="submit">提交</button>
  </form>
</div>

</body>
</html>

4、在\resources\template創建insertPage.html添加頁面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>添加用戶</title>
  <link rel="stylesheet" type="text/css" th:href="@{/css/bootstrap.css}"/>
</head>

<body>

<div style="width:800px;height:100%;margin-left:270px;">
  <form action="/user/insert" method="post">
    姓名:<input class="form-control" type="text" th:value="${name}" name="name"><br>
    年齡:<input class="form-control" type="text" th:value="${age}" name="age"><br>
    性別:<input class="form-control" type="text" th:value="${sex}" name="sex"><br>
    地址:<input class="form-control" type="text" th:value="${address}" name="address"><br>
    <button class="btn btn-primary btn-lg btn-block">保存</button>
  </form>
</div>

</body>
</html>

五、項目

在這裏插入圖片描述

六、運行

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

代碼下載

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章