網站首頁 編程語言 正文
目錄
- 項目架構
- 數據庫
- 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);
/**
* 根據ID查找用戶
*/
@Select("select * from user where id=#{id}")
public User get(int id);
/**
* 根據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);
/**
* 根據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";
}
/**
* 根據id修改用戶數據
*/
@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
,即可進入用戶信息主頁面。
原文鏈接:https://blog.csdn.net/hutianle/article/details/125783304
相關推薦
- 2022-10-20 C++?float、double判斷是否等于0問題_C 語言
- 2022-10-24 C#?Winform實現自定義漂亮的通知效果_C#教程
- 2022-09-22 登錄、注冊相關業務邏輯(模擬登錄、注冊)-H5本地存儲
- 2023-07-29 git如何配置多個SSH
- 2023-04-18 獲取Android簽名MD5的方式實例詳解_Android
- 2022-08-26 docker搭建memcached的詳細步驟_docker
- 2022-02-26 C:\Users\用戶名\AppData\Roaming里面的文件可以刪除嗎?
- 2022-04-26 Python中的3D繪圖命令總結_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支