網(wǎng)站首頁(yè) 編程語(yǔ)言 正文
目錄
- 項(xiàng)目架構(gòu)
- 數(shù)據(jù)庫(kù)
- POJO
- Dao
- Service
- Controller
- 前端頁(yè)面
- 配置文件
- 運(yùn)行
項(xiàng)目架構(gòu)
本項(xiàng)目為Spring Boot入門(mén)——增刪改查案例。
前端采用html + thymeleaf
模板代替jsp
項(xiàng)目架構(gòu)如下:
.
├── src
│ ├── main
│ │ ├── java
│ │ │ └── com.example
│ │ │ └── crud --業(yè)務(wù)功能模塊 即 CRUD
│ │ │ ├── controller --Controller層
│ │ │ │ └── UserControl
│ │ │ ├── dao --Dao層
│ │ │ │ └── UserDao --Dao層接口
│ │ │ ├── pojo --數(shù)據(jù)模型
│ │ │ │ └── User --請(qǐng)求體
│ │ │ ├── service --Service層
│ │ │ │ ├── impl --Service層接口的實(shí)現(xiàn)
│ │ │ │ │ └── UserServiceImpl
│ │ │ │ └── UserService --Service層接口
│ │ │ └── Application.java --啟動(dòng)類(lèi)
│ │ └── resources
│ │ ├── static --靜態(tài)資源
│ │ ├── template --模板
│ │ ├── add.html --增加用戶(hù)頁(yè)面
│ │ ├── index.html --主頁(yè)面
│ │ └── modify.html --修改用戶(hù)頁(yè)面
└── pom.xml --項(xiàng)目依賴(lài)
數(shù)據(jù)庫(kù)
MySQL:v8.0.29
Navicat Premium 15
新建連接:crud
新建數(shù)據(jù)庫(kù):springboot_crud
表:user
包含三個(gè)字段:id,username,password
user表如下:
id | username | password |
---|---|---|
1 | Lebron | 1111 |
2 | Durant | 2222 |
3 | Curry | 3333 |
4 | Bryant | 4444 |
5 | Harden | 5555 |
建表SQL語(yǔ)句:
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
下包含實(shí)體類(lèi)User
。
實(shí)體類(lèi)有三個(gè)私有成員變量:id
,username
,password
。
這三個(gè)屬性分別與數(shù)據(jù)庫(kù)springboot_crud
中的表user
相對(duì)應(yīng)。
實(shí)體類(lèi)User
包含帶參構(gòu)造方法、無(wú)參構(gòu)造方法、三個(gè)屬性對(duì)應(yīng)的get
和set
方法,另外還包含一個(gè)重寫(xiě)的toString
方法。
實(shí)體類(lèi)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用于修飾接口內(nèi)的方法(增刪改查)。
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 {
/**
* 查詢(xún)?nèi)繑?shù)據(jù)
*/
@Select("select * from user")
public List<User> findAll();
**
* 新增數(shù)據(jù)
*/
@Insert("insert into user (username, password) values (#{username}, #{password})")
public int save(User user);
/**
* 刪除數(shù)據(jù)
*/
@Delete("delete from user where id=#{id}")
public int delete(int id);
/**
* 根據(jù)ID查找用戶(hù)
*/
@Select("select * from user where id=#{id}")
public User get(int id);
/**
* 根據(jù)ID更新用戶(hù)數(shù)據(jù)
*/
@Update("update user set username=#{username},password=#{password} where id=#{id}")
public int updateById(User user);
}
Service
包service
下包含包impl
和Service層的接口UserService
其中,包impl
包含Service層接口的實(shí)現(xiàn)類(lèi)UserServiceImpl
Service層
既需要調(diào)用Dao層接口
,又需要提供接口給Controller層
的類(lèi)進(jìn)行調(diào)用。
接口UserService.java
package com.example.crud.service;
import com.example.crud.pojo.User;
import java.util.List;
public interface UserService {
/**
* 查詢(xún)?nèi)繑?shù)據(jù)
*/
public List<User> findAll();
/**
* 新增數(shù)據(jù)
*/
public int save(User user);
/**
* 刪除數(shù)據(jù)
*/
public int delete(int id);
/**
* 根據(jù)ID查找
*/
public User get(int id);
/**
* 更新數(shù)據(jù)
*/
public int updateById(User user);
}
接口實(shí)現(xiàn)類(lèi)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
包含類(lèi)UserControl
。
注解@Controller用于修飾類(lèi)UserControl
。
注解@Autowired表示自動(dòng)注入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;
/**
* 查詢(xún)所有用戶(hù)數(shù)據(jù)
*/
@GetMapping("/index.html")
public String userList(Map<String, List> result) {
List<User> users = userService.findAll();
result.put("users", users);
return "index";
}
/**
* 新增數(shù)據(jù)
*/
@PostMapping("/add")
public String save(User user) {
userService.save(user);
return "redirect:/index.html";
}
/**
* 刪除數(shù)據(jù)
*/
@RequestMapping("/delete/{id}")
public String delete(@PathVariable int id, HttpServletResponse servletResponse) throws IOExceptioon {
userService.delete(id);
System.out.println("----delete方法執(zhí)行----");
return "redirect:/index.html";
}
/**
* 根據(jù)id修改用戶(hù)數(shù)據(jù)
*/
@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";
}
}
前端頁(yè)面
包resources
下的包templates
下有三個(gè)html文件。
?刪除按鈕添加了onclick="return confirm('確定刪除?')"
防止誤操作。
主頁(yè)面index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用戶(hù)信息主頁(yè)面</title>
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<style>
a{
color: #ffffff;
}
h1{
/*文字對(duì)齊*/
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:斑馬線(xiàn)格式,table-bordered:帶邊框,table-hover:鼠標(biāo)懸停高亮-->
<table class="table table-striped table-bordered table-hover text-center">
<thead>
<tr style="text-align:center">
<!--th標(biāo)簽定義html表格中的表頭單元格-->
<th style="text-align:center">編號(hào)</th>
<th style="text-align:center">用戶(hù)名</th>
<th style="text-align:center">密碼</th>
<th style="text-align:center">操作</th>
</tr>
</thead>
<!--tr標(biāo)簽定義html表格中的所有行-->
<!--遍歷集合,如果被遍歷的變量user為null或者不存在,則不會(huì)進(jìn)行遍歷,也不會(huì)報(bào)錯(cuò)-->
<tr th:each="user:${users}">
<!--td標(biāo)簽定義html表格中的標(biāo)準(zhǔn)單元格-->
<td th:text="${user.id}"></td>
<td th:text="${user.username}"></td>
<td th:text="${user.password}"></td>
<td>
<!--a標(biāo)簽用來(lái)定義超鏈接 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">添加用戶(hù)</a></button>
</div>
</body>
</html>
添加用戶(hù)頁(yè)面add.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>添加用戶(hù)頁(yè)面</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添加這個(gè)class后就會(huì)使用bootstrap自帶的input框-->
用戶(hù)名:<input class="form-control" type="text" th:value="${username}" name="username"><br>
<!--注意參數(shù)的拼接-->
密 碼:<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>
更改用戶(hù)信息界面modify.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>更改用戶(hù)信息界面</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風(fēng)格中的更新是put請(qǐng)求,所以這塊先使用post請(qǐng)求,然后隱藏起來(lái)改為put請(qǐng)求-->
<input name="_method" type="hidden" value="put">
ID:<input class="form-control" type="text" th:value="${user.id}" name="id"><br>
用戶(hù)名:<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 # 設(shè)置開(kāi)啟熱部署
freemarker:
cache: false # 頁(yè)面不加載緩存,修改即使生效
mybatis:
configuration:
map-underscore-to-camel-case: true # 下劃線(xiàn)駝峰設(shè)置
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 打印SQL語(yǔ)句
運(yùn)行
在chrome瀏覽器中輸入http://localhost:8080/index.html
,即可進(jìn)入用戶(hù)信息主頁(yè)面。
原文鏈接:https://blog.csdn.net/hutianle/article/details/125783304
相關(guān)推薦
- 2022-09-15 C語(yǔ)言實(shí)現(xiàn)簡(jiǎn)單的推箱子小游戲_C 語(yǔ)言
- 2022-07-29 Linux文件管理方法介紹_linux shell
- 2022-10-25 Python繪制loss曲線(xiàn)和準(zhǔn)確率曲線(xiàn)實(shí)例代碼_python
- 2022-11-09 WPF使用WrapPanel實(shí)現(xiàn)虛擬化效果_C#教程
- 2023-01-03 C#短消息提示窗口位置及窗口大小詳解_C#教程
- 2022-10-13 云服務(wù)器Windows?Server2012配置FTP服務(wù)器詳細(xì)圖文教程_FTP服務(wù)器
- 2022-11-05 Android?TabLayout?自定義樣式及使用詳解_Android
- 2022-04-07 淺談C++11中=delete的巧妙用法_C 語(yǔ)言
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過(guò)濾器
- Spring Security概述快速入門(mén)
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支