SpringBoot + Thymeleaf 实现单表的增删改查
前言前端:Thymeleaf后端:SpringBoot、Mybatis数据库:MySQL工具:IDEA环境:JDK1.8、Tomcat 8、Maven一、创建表,添加数据1、创建数据库:CREATE table users (id int(20) auto_increment primary key,name VARCHAR(20) not null,age int(20) not null,se
·
前言
一、创建表,添加数据
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>  
<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>
五、项目
六、运行
代码下载
更多推荐
已为社区贡献3条内容
所有评论(0)