目录
- 项目架构
- 数据库
- POJO
- Dao
- Service
- Controller
- 前端页面
- 配置文件
- 运行
项目架构
本项目为Spring Boot入门——增删改查案例。
前端采用html + thymeleaf
模板代替jsp
项目架构如下:
.
├── src
│ ├── main
│ │ ├── java
│ │ │ └── com.example
│ │ │ └── crud --业务功能模块 即 CRUD
│ │ │ ├── controller --Controller层
│ │ │ │ └── UserControl
│ │ │ ├── dao --Dao层
│ │ │ │ └── UserDao --Dao层接口
│ │ │ ├── pojo --数据模型
│ │ │ │ └── User --请求体
│ │ │ ├── service --Service层
│ │ │ │ ├── impl --Service层接口的实现
│ │ │ │ │ └── UserServiceImpl
│ │ │ │ └── UserService --Service层接口
│ │ │ └── Application.java --启动类
│ │ └── resources
│ │ ├── static --静态资源
│ │ ├── template --模板
│ │ ├── add.html --增加用户页面
│ │ ├── index.html --主页面
│ │ └── modify.html --修改用户页面
└── pom.xml --项目依赖
数据库
MySQL:v8.0.29
Navicat Premium 15
新建连接:crud
新建数据库:springboot_crud
表:user
包含三个字段:id,username,password
user表如下:
id |
username |
password |
1 |
Lebron |
1111 |
2 |
Durant |
2222 |
3 |
Curry |
3333 |
4 |
Bryant |
4444 |
5 |
Harden |
5555 |
建表SQL语句:
CREATE TABLE `user` (
`id` int NOT NULL AUTO_INCREMENT,
`username` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`password` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
POJO
包pojo
下包含实体类User
。
实体类有三个私有成员变量:id
,username
,password
。
这三个属性分别与数据库springboot_crud
中的表user
相对应。
实体类User
包含带参构造方法、无参构造方法、三个属性对应的get
和set
方法,另外还包含一个重写的toString
方法。
实体类User.java
package com.example.crud.pojo;
public class User {
private Integer id;
private String username;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User(Integer id,String username,String password) {
this.id=id;
this.username=username;
this.password=password;
}
public User() {
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
Dao
包dao
下包含接口UserDao
。
注解@Mapper用于修饰接口UserDao
。
注解@Insert、@Delete、@Update、@Select用于修饰接口内的方法(增删改查)。
UserDao.java
package com.example.crud.mapper;
import com.example.crud.pojo.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface UserMapper {
@Select("select * from user")
public List<User> findAll();
**
* 新增数据
*/
@Insert("insert into user (username, password) values (#{username}, #{password})")
public int save(User user);
@Delete("delete from user where id=#{id}")
public int delete(int id);
@Select("select * from user where id=#{id}")
public User get(int id);
@Update("update user set username=#{username},password=#{password} where id=#{id}")
public int updateById(User user);
}
Service
包service
下包含包impl
和Service层的接口UserService
其中,包impl
包含Service层接口的实现类UserServiceImpl
Service层
既需要调用Dao层接口
,又需要提供接口给Controller层
的类进行调用。
接口UserService.java
package com.example.crud.service;
import com.example.crud.pojo.User;
import java.util.List;
public interface UserService {
public List<User> findAll();
public int save(User user);
public int delete(int id);
public User get(int id);
public int updateById(User user);
}
接口实现类UserServiceImpl.java
package com.example.crud.service.impl;
import com.example.crud.mapper.UserMapper;
import com.example.crud.pojo.User;
import com.example.crud.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public List<User> findAll() {
return userDao.findAll();
}
@Override
public int save(User user) {
return userDao.save(user);
}
@Override
public int delete(int id) {
return userDao.delete(id);
}
@Override
public User get(int id) {
return userDao.get(id);
}
@Override
public int updateById(User user) {
return userDao.updateById(user);
}
}
Controller
包controller
包含类UserControl
。
注解@Controller用于修饰类UserControl
。
注解@Autowired表示自动注入Service层
提供的接口,供Controller层
使用。
UserControl.java
package com.example.crud.controller;
import com.example.crud.pojo.User;
import com.example.crud.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
@Controller
public class UserControl {
@Autowired
private UserService userservice;
@GetMapping("/index.html")
public String userList(Map<String, List> result) {
List<User> users = userService.findAll();
result.put("users", users);
return "index";
}
@PostMapping("/add")
public String save(User user) {
userService.save(user);
return "redirect:/index.html";
}
@RequestMapping("/delete/{id}")
public String delete(@PathVariable int id, HttpServletResponse servletResponse) throws IOExceptioon {
userService.delete(id);
System.out.println("----delete方法执行----");
return "redirect:/index.html";
}
@GetMapping("/updatePage/{id}")
public String updatePage(Model model, @PathVariable int id) {
User users = userService.get(id);
model.addAttribute("users", users);
return "modify";
}
@PutMapping("/update")
public String updateUser(Model model, User user, HttpServletRequest request) {
String id = request.getParameter("id");
User userById = userService.get(Integer.parseInt(id));
userService.updataById(user);
System.out.println(user);
return "redirect:/index.html";
}
}
前端页面
包resources
下的包templates
下有三个html文件。
⭐删除按钮添加了onclick="return confirm('确定删除?')"
防止误操作。
主页面index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用户信息主页面</title>
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<style>
a{
color: #ffffff;
}
h1{
text-align: center;
}
button{
height: 50px;
width: 50px;
background-color: cornflowerblue;
}
.parent{
display: flex;
justify-content: center;
align-items: center;
}
.btn{
width: auto;
}
</style>
<body>
<h1>Spring Boot增删改查</h1>
<!--table-striped:斑马线格式,table-bordered:带边框,table-hover:鼠标悬停高亮-->
<table class="table table-striped table-bordered table-hover text-center">
<thead>
<tr style="text-align:center">
<!--th标签定义html表格中的表头单元格-->
<th style="text-align:center">编号</th>
<th style="text-align:center">用户名</th>
<th style="text-align:center">密码</th>
<th style="text-align:center">操作</th>
</tr>
</thead>
<!--tr标签定义html表格中的所有行-->
<!--遍历集合,如果被遍历的变量user为null或者不存在,则不会进行遍历,也不会报错-->
<tr th:each="user:${users}">
<!--td标签定义html表格中的标准单元格-->
<td th:text="${user.id}"></td>
<td th:text="${user.username}"></td>
<td th:text="${user.password}"></td>
<td>
<!--a标签用来定义超链接 href表示超链接-->
<a class="btn btn-primary" th:href="@{'/updatePage/'+${user.id}}">更改</a>
<a class="btn btn-danger" th:href="@{'/delete/'+${user.id}}" onclick="return confirm('确定删除?')">删除</a>
</td>
</tr>
</table>
<div class="parent">
<button type="button" class="btn btn-block"><a href="/add.html">添加用户</a></button>
</div>
</body>
</html>
添加用户页面add.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>添加用户页面</title>
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<sty>
<body>
<div style="width:600px;height:100%;margin-left:350px;margin-top: 180px;">
<form action="/add" method="post">
<!--form-control给input添加这个class后就会使用bootstrap自带的input框-->
用户名:<input class="form-control" type="text" th:value="${username}" name="username"><br>
<!--注意参数的拼接-->
密 码:<input class="form-control" type="text" th:value="${password}" name="password"><br>
<button class="btn btn-primary btn-lg btn-block">保存</button>
</form>
</div>
</body>
</html>
更改用户信息界面modify.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>更改用户信息界面</title>
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div style="width:600px;height:100%;margin-left:350px;margin-top: 180px;">
<form action="/update" method="post">
<!-- rest风格中的更新是put请求,所以这块先使用post请求,然后隐藏起来改为put请求-->
<input name="_method" type="hidden" value="put">
ID:<input class="form-control" type="text" th:value="${user.id}" name="id"><br>
用户名:<input class="form-control" type="text" th:value="${user.username}" name="username"><br>
密 码:<input class="form-control" type="text" th:value="${user.password}" name="password"><br>
<button class="btn btn-primary btn-lg btn-block" type="submit">提交</button>
</form>
</div>
</body>
</html>
配置文件
application.yml
spring:
web:
resources:
static-locations: classpath:/static/,classpath:/templates/
datasource:
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mysql://localhost:3306/springboot_crud?useSSL=false
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
mvc:
hiddenmethod:
filter:
enabled: true
devtools:
restart:
enabled: true # 设置开启热部署
freemarker:
cache: false # 页面不加载缓存,修改即使生效
mybatis:
configuration:
map-underscore-to-camel-case: true # 下划线驼峰设置
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 打印SQL语句
运行
在chrome浏览器中输入http://localhost:8080/index.html
,即可进入用户信息主页面。