1. Spring MVC 中 使用 RESTFul 实现用户管理系统
文章目录
- 1. Spring MVC 中 使用 RESTFul 实现用户管理系统
- 2. 静态页面准备
- 2.1 user.css
- 2.2 user_index.html
- 2.3 user_list.html
- 2.4 user_add.html
- 2.5 user_edit.html
- 3. SpringMVC环境搭建
- 3.1 创建module:usermgt
- 3.2 添加web支持
- 3.3 配置web.xml文件
- 3.4 配置springmvc.xml文件
- 4. 对应具体功能的实现
- 4.1 显示首页
- 4.2 实现用户列表
- 4.3 实现新增功能
- 4.3.1 跳转到新增页面
- 4.3.2 实现新增功能
- 4.4 跳转到修改页面
- 4.5 实现修改功能
- 4.6 实现删除功能
- 5. 补充:
- 最后:
2. 静态页面准备
2.1 user.css
文件包括:user.css、user_index.html、user_list.html、user_add.html、user_edit.html。代码如下:
.header {
background-color: #f2f2f2;
padding: 20px;
text-align: center;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
}
li {
float: left;
}
li a {
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
li a:hover:not(.active) {
background-color: #111;
}
.active {
background-color: #4CAF50;
}
form {
width: 50%;
margin: 0 auto;
padding: 20px;
border: 1px solid #ddd;
border-radius: 4px;
}
label {
display: block;
margin-bottom: 8px;
}
input[type="text"], input[type="email"], select {
width: 100%;
padding: 6px 10px;
margin: 8px 0;
box-sizing: border-box;
border: 1px solid #555;
border-radius: 4px;
font-size: 16px;
}
button[type="submit"] {
padding: 10px;
background-color: #4CAF50;
color: #fff;
border: none;
border-radius: 4px;
cursor: pointer;
}
button[type="submit"]:hover {
background-color: #3e8e41;
}
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}
.header {
background-color: #f2f2f2;
padding: 20px;
text-align: center;
}
a {
text-decoration: none;
color: #333;
}
.add-button {
margin-bottom: 20px;
padding: 10px;
background-color: #4CAF50;
color: #fff;
border: none;
border-radius: 4px;
cursor: pointer;
}
.add-button:hover {
background-color: #3e8e41;
}
2.2 user_index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用户管理系统</title>
<link rel="stylesheet" th:href="@{static/css/user.css}" type="text/css"></link>
</head>
<body>
<div class="header">
<h1>用户管理系统</h1>
</div>
<ul>
<li><a class="active" th:href="@{/user}">用户列表</a></li>
</ul>
</body>
</html>
2.3 user_list.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用户列表</title>
<link rel="stylesheet" th:href="@{static/css/user.css}" type="text/css"></link>
</head>
<body>
<div class="header">
<h1>用户列表</h1>
</div>
<div class="add-button-wrapper">
<a class="add-button" th:href="@{/toAdd}">新增用户</a>
</div>
<table>
<thead>
<tr>
<th>编号</th>
<th>用户名</th>
<th>性别</th>
<th>邮箱</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr th:each="user : ${users}">
<td th:text="${user.id}"></td>
<td th:text="${user.username}"></td>
<td th:text="${user.sex == 1 ? '男' : '女'}"></td>
<td th:text="${user.email}"></td>
<td>
<!-- 将 id 传过去,进行修改-->
<a th:href="@{'/user/'+ ${user.id}}">修改</a>
<a th:href="@{'/user/'+ ${user.id}}" onclick="del(event)">删除</a>
</td>
</tr>
</tbody>
</table>
<!--为删除操作准备一个form表单,点击删除时提交form表单-->
<div style="display: none">
<form method="post" id="delForm">
<!-- 删除是 delte 请求-->
<input type="hidden" name="_method" value="delete"/>
</form>
</div>
<script>
function del(event) {
// 获取表单
let delForm = document.getElementById("delForm");
// 设置表单action ev
delForm.action = event.target.href;
if (window.confirm("您确定要删除吗?")) {
// 提交表单
delForm.submit();
}
// 阻止超链接默认行为
event.preventDefault();
}
</script>
<!--java.lang.IllegalArgumentException: Name for argument of type [java.lang.Long] not specified, and parameter name information not available via reflection. Ensure that the compiler uses the '-parameters' flag.-->
</body>
</html>
2.4 user_add.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" >
<title>新增用户</title>
<link rel="stylesheet" th:href="@{static/css/user.css}" type="text/css"></link>
</head>
<body>
<h1>新增用户</h1>
<form th:action="@{/user}" method="post">
<label>用户名:</label>
<input type="text" name="username" required>
<label>性别:</label>
<select name="gender" required>
<option value="">-- 请选择 --</option>
<option value="1">男</option>
<option value="0">女</option>
</select>
<label>邮箱:</label>
<input type="email" name="email" required>
<button type="submit">保存</button>
</form>
</body>
</html>
2.5 user_edit.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" >
<title>修改用户</title>
<link rel="stylesheet"th:href="@{static/css/user.css}"type="text/css"></link>
</head>
<body>
<h1>修改用户</h1>
<form th:action="@{/user}" method="post">
<!--隐藏域的方式设置请求方式为put请求-->
<!-- 修改是 put 请求-->
<input type="hidden" name="_method" value="put">
<!--隐藏域的方式提交id-->
<input type="hidden" name="id" th:value="${user.id}">
<label>用户名:</label>
<input type="text" name="username" th:value="${user.username}" required>
<label>性别:</label>
<select name="sex" required>
<option value="">-- 请选择 --</option>
<option value="1" th:field="${user.sex}">男</option>
<option value="0" th:field="${user.sex}">女</option>
</select>
<label>邮箱:</label>
<input type="email" name="email" th:value="${user.email}" required>
<button type="submit">修改</button>
</form>
</body>
</html>
3. SpringMVC环境搭建
3.1 创建module:usermgt
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.powernode</groupId>
<artifactId>usermgt</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<!--springmvc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>6.1.5</version>
</dependency>
<!--servlet api-->
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.0.0</version>
</dependency>
<!--logback-->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.5.3</version>
</dependency>
<!--thymeleaf+spring6整合依赖-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring6</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
3.2 添加web支持
3.3 配置web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd"
version="6.0">
<!--字符编码过滤器-->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--HTTP请求方式过滤器-->
<filter>
<filter-name>hiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--前端控制器-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
注意两个过滤器Filter的配置顺序:
-
先配置 CharacterEncodingFilter
-
再配置 HiddenHttpMethodFilter
不然,可能获取的的中文信息数据是乱码
3.4 配置springmvc.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--组件扫描-->
<context:component-scan base-package="com.powernode.usermgt.controller,com.powernode.usermgt.dao"/>
<!--视图解析器-->
<bean id="thymeleafViewResolver" class="org.thymeleaf.spring6.view.ThymeleafViewResolver">
<property name="characterEncoding" value="UTF-8"/>
<property name="order" value="1"/>
<property name="templateEngine">
<bean class="org.thymeleaf.spring6.SpringTemplateEngine">
<property name="templateResolver">
<bean class="org.thymeleaf.spring6.templateresolver.SpringResourceTemplateResolver">
<property name="prefix" value="/WEB-INF/thymeleaf/"/>
<property name="suffix" value=".html"/>
<property name="templateMode" value="HTML"/>
<property name="characterEncoding" value="UTF-8"/>
</bean>
</property>
</bean>
</property>
</bean>
<!--开启注解-->
<mvc:annotation-driven/>
<!--开启默认Servlet-->
<mvc:default-servlet-handler/>
</beans>
在WEB-INF目录下新建:thymeleaf目录
创建 package:
4. 对应具体功能的实现
4.1 显示首页
在应用的根下新建目录:static,将user.css文件拷贝进去。
将user_index.html拷贝到WEB-INF/thymeleaf目录下:
代码有两处需要修改:
重要:在springmvc.xml文件中配置视图控制器映射:
<!--视图控制器映射-->
<mvc:view-controller path="/" view-name="user_index"/>
部署,启动服务器,测试
4.2 实现用户列表
修改user_index.html中的超链接:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用户管理系统</title>
<link rel="stylesheet" th:href="@{/static/user.css}" type="text/css"></link>
</head>
<body>
<div class="header">
<h1>用户管理系统</h1>
</div>
<ul>
<li><a class="active" th:href="@{/user}">用户列表</a></li>
</ul>
</body>
</html>
编写bean:User
package com.rainbowsea.usermgt.bean;
public class User {
/**
* 用户编号
*/
private Long id;
/**
* 用户名
*/
private String username;
/**
* 性别
* 1 表示男
* 2 表示女
*/
private Integer sex;
/**
* 邮箱
*/
private String email;
public User() {
}
public User(Long id, String username, Integer sex, String email) {
this.id = id;
this.username = username;
this.sex = sex;
this.email = email;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", sex=" + sex +
", email='" + email + '\'' +
'}';
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
编写UserDao,提供selectAll方法:
import com.powernode.usermgt.bean.User;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
@Repository
public class UserDao {
private static List<User> users = new ArrayList<>();
static {
User user1 = new User(10001L, "张三", "zhangsan@powernode.com", 1);
User user2 = new User(10002L, "李四", "lisi@powernode.com", 1);
User user3 = new User(10003L, "王五", "wangwu@powernode.com", 1);
User user4 = new User(10004L, "赵六", "zhaoliu@powernode.com", 0);
User user5 = new User(10005L, "钱七", "qianqi@powernode.com", 0);
users.add(user1);
users.add(user2);
users.add(user3);
users.add(user4);
users.add(user5);
}
public List<User> selectAll(){
return users;
}
}
编写控制器UserController:
import com.powernode.usermgt.bean.User;
import com.powernode.usermgt.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.List;
@Controller
public class UserController {
@Autowired
private UserDao userDao;
@GetMapping("/user")
public String list(Model model){
// 获取所有的用户
List<User> users = userDao.selectAll();
// 存储到request域
model.addAttribute("users", users);
// 跳转视图
return "user_list";
}
}
将user_list.html拷贝到thymeleaf目录下,并进行代码修改,显示用户列表:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用户列表</title>
<link rel="stylesheet" th:href="@{/static/user.css}" type="text/css"></link>
</head>
<body>
<div class="header">
<h1>用户列表</h1>
</div>
<div class="add-button-wrapper">
<a class="add-button" href="user_add.html">新增用户</a>
</div>
<table>
<thead>
<tr>
<th>编号</th>
<th>用户名</th>
<th>性别</th>
<th>邮箱</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr th:each="user : ${users}">
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.gender == 1 ? '男' : '女'}"></td>
<td th:text="${user.email}"></td>
<td>
<a href="">修改</a>
<a href="">删除</a>
</td>
</tr>
</tbody>
</table>
</body>
</html>
测试结果:
4.3 实现新增功能
4.3.1 跳转到新增页面
在用户列表页面,修改新增用户
的超链接:
将user_add.html拷贝到thymeleaf目录下,并进行代码修改如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http:www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>新增用户</title>
<link rel="stylesheet" th:href="@{/static/user.css}" type="text/css"></link>
</head>
<body>
<h1>新增用户</h1>
<form>
<label>用户名:</label>
<input type="text" name="username" required>
<label>性别:</label>
<select name="gender" required>
<option value="">-- 请选择 --</option>
<option value="1">男</option>
<option value="0">女</option>
</select>
<label>邮箱:</label>
<input type="email" name="email" required>
<button type="submit">保存</button>
</form>
</body>
</html>
在springmvc.xml文件中配置视图控制器映射
:
<mvc:view-controller path="/toSave" view-name="user_add"/>
启动服务器测试:
4.3.2 实现新增功能
前端页面发送POST请求,提交表单,user_add.html代码如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http:www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>新增用户</title>
<link rel="stylesheet" th:href="@{/static/user.css}" type="text/css"></link>
</head>
<body>
<h1>新增用户</h1>
<form th:action="@{/user}" method="post">
<label>用户名:</label>
<input type="text" name="name" required>
<label>性别:</label>
<select name="gender" required>
<option value="">-- 请选择 --</option>
<option value="1">男</option>
<option value="0">女</option>
</select>
<label>邮箱:</label>
<input type="email" name="email" required>
<button type="submit">保存</button>
</form>
</body>
</html>
编写控制器UserController:
@PostMapping("/user")
public String save(User user){
// 保存用户
userDao.save(user);
// 重定向到列表
return "redirect:/user";
}
注意:保存成功后,采用重定向的方式跳转到用户列表。
编写UserDao:
public static Long generateId(){
// Stream API
Long maxId = users.stream().map(user -> user.getId()).reduce((id1, id2) -> id1 > id2 ? id1 : id2).get();
return maxId + 1;
}
public void save(User user){
// 设置id
user.setId(generateId());
// 保存
users.add(user);
}
注意:单独写了一个方法生成id,内部使用了Stream API,不会这块内容的可以看老杜最新发布的2024版JavaSE。
启动服务器测试:
4.4 跳转到修改页面
修改user_list.html中修改
超链接:
<a th:href="@{'/user/' + ${user.id}}">修改</a>
编写Controller:
@GetMapping("/user/{id}")
public String toUpdate(@PathVariable("id") Long id, Model model){
// 根据id查询用户信息
User user = userDao.selectById(id);
// 将对象存储到request域
model.addAttribute("user", user);
// 跳转视图
return "user_edit";
}
编写UserDao:
public User selectById(Long id){
return users.stream().filter(user -> user.getId().equals(id)).findFirst().get();
}
将user_edit.html拷贝thymeleaf目录下,并修改代码如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>修改用户</title>
<link rel="stylesheet" th:href="@{/static/user.css}" type="text/css"></link>
</head>
<body>
<h1>修改用户</h1>
<form>
<label>用户名:</label>
<input type="text" name="username" th:value="${user.name}" required>
<label>性别:</label>
<select name="gender" required>
<option value="">-- 请选择 --</option>
<option value="1" th:field="${user.gender}">男</option>
<option value="0" th:field="${user.gender}">女</option>
</select>
<label>邮箱:</label>
<input type="email" name="email" th:value="${user.email}" required>
<button type="submit">修改</button>
</form>
</body>
</html>
启动服务器测试:
4.5 实现修改功能
将user_edit.html页面中的form表单修改一下,添加action,添加method,隐藏域的方式提交请求方式put,隐藏域的方式提交id:
<form th:action="@{/user}" method="post">
<!--隐藏域的方式设置请求方式为put请求-->
<input type="hidden" name="_method" value="put">
<!--隐藏域的方式提交id-->
<input type="hidden" name="id" th:value="${user.id}">
<label>用户名:</label>
<input type="text" name="name" th:value="${user.name}" required>
<label>性别:</label>
<select name="gender" required>
<option value="">-- 请选择 --</option>
<option value="1" th:field="${user.gender}">男</option>
<option value="0" th:field="${user.gender}">女</option>
</select>
<label>邮箱:</label>
<input type="email" name="email" th:value="${user.email}" required>
<button type="submit">修改</button>
</form>
编写Controller:
@PutMapping("/user")
public String modify(User user){
// 更新数据
userDao.update(user);
// 重定向
return "redirect:/user";
}
编写UserDao:
public void update(User user){
for (int i = 0; i < users.size(); i++) {
if(user.getId().equals(users.get(i).getId())){
users.set(i, user);
break;
}
}
}
启动服务器测试:
4.6 实现删除功能
删除应该发送DELETE请求,要模拟DELETE请求,就需要使用表单方式提交。因此我们点击删除超链接时需要采用表单方式提交。 在user_list.html页面添加form表单,并且点击超链接时应该提交表单,代码如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用户列表</title>
<link rel="stylesheet" th:href="@{/static/user.css}" type="text/css"></link>
</head>
<body>
<div class="header">
<h1>用户列表</h1>
</div>
<div class="add-button-wrapper">
<a class="add-button" th:href="@{/toSave}">新增用户</a>
</div>
<table>
<thead>
<tr>
<th>编号</th>
<th>用户名</th>
<th>性别</th>
<th>邮箱</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr th:each="user : ${users}">
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.gender == 1 ? '男' : '女'}"></td>
<td th:text="${user.email}"></td>
<td>
<a th:href="@{'/user/' + ${user.id}}">修改</a>
<!--为删除提供一个鼠标单击事件-->
<a th:href="@{'/user/' + ${user.id}}" onclick="del(event)">删除</a>
</td>
</tr>
</tbody>
</table>
<!--为删除操作准备一个form表单,点击删除时提交form表单-->
<div style="display: none">
<form method="post" id="delForm">
<input type="hidden" name="_method" value="delete"/>
</form>
</div>
<script>
function del(event){
// 获取表单
let delForm = document.getElementById("delForm");
// 设置表单action
delForm.action = event.target.href;
if(window.confirm("您确定要删除吗?")){
// 提交表单
delForm.submit();
}
// 阻止超链接默认行为
event.preventDefault();
}
</script>
</body>
</html>
编写Controller:
@DeleteMapping("/user/{id}")
public String del(@PathVariable("id") Long id){
// 删除
userDao.deleteById(id);
// 重定向
return "redirect:/user";
}
编写UserDao:
public void deleteById(Long id){
for (int i = 0; i < users.size(); i++) {
if(id.equals(users.get(i).getId())){
users.remove(i);
break;
}
}
}
启动服务器测试:
5. 补充:
完整的 Controller类的内容:
package com.rainbowsea.usermgt.controller;
import com.rainbowsea.usermgt.bean.User;
import com.rainbowsea.usermgt.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.List;
@Controller // 交给 Spring IOC 容器管理
public class UserController {
@Autowired // 自动赋值
private UserDao userDao; // Could not autowire. No beans of 'UserDao' type found.
@RequestMapping(value = "/user", method = RequestMethod.GET)
public String list(Model model) {
// 查询数据库,获取用户列表List集合
List<User> users = userDao.selectAll();
// 将用户列表存储到 request 域当中
model.addAttribute("users", users);
// 转发到视图
return "user_list";
}
@RequestMapping(value = "/user", method = RequestMethod.POST)
public String save(User user) {
// 调用 userDao保存用户信息
userDao.insert(user);
// 重定向到用户列表页面(重新让浏览器发送一次全新的请求,去请求列表页面)
return "redirect:/user";
}
@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
public String detail(@PathVariable(value = "id") Long id, Model model) {
// 通过 id 查找用户信息
User user = userDao.selectById(id);
// 将用户休息存储到 request 域当中
model.addAttribute("user", user);
// 转发到视图
return "user_edit";
}
@RequestMapping(value = "/user", method = RequestMethod.PUT)
public String modify(User user) {
// 修改用户信息
userDao.upate(user);
// 重定向列表页面
return "redirect:/user";
}
@RequestMapping(value = "/user/{id}",method = RequestMethod.DELETE)
public String del(@PathVariable(value = "id") Long id) {
// 调用 dao删除用户
userDao.deleteByid(id);
// 重定向到列表
return "redirect:/user";
}
}
完整的 UserDao 类内容:
package com.rainbowsea.usermgt.dao;
import com.rainbowsea.usermgt.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
@Repository // 交给 Spring IOC 容器管理
public class UserDao {
private static List<User> users = new ArrayList<>();
static {
// 类加载是初始化数据
// 创建 User 对象
User user1 = new User(1001L, "张三", 2, "zhangsan@rainbowsea.com");
User user2 = new User(1002L, "李四", 2, "lisin@rainbowsea.com");
User user3 = new User(1003L, "李华", 2, "lihua@rainbowsea.com");
User user4 = new User(1004L, "小红", 1, "xiaohong@rainbowsea.com");
User user5 = new User(1005L, "小智", 1, "xiaozhi@rainbowsea.com");
users.add(user1);
users.add(user2);
users.add(user3);
users.add(user4);
users.add(user5);
// 将 User 对象存储到 List 集合中
}
/**
* 查询所有的用户信息
*
* @return
*/
public List<User> selectAll() {
return users;
}
/**
* 专门生成 ID的
* 找到其中的最大值 + 1
*
* @return
*/
public Long generateld() {
// 使用 Steam API
Long maxId = users.stream().map(user -> user.getId()).reduce((id1, id2) -> id1 > id2 ? id1 : id2).get();
return maxId + 1;
}
/**
* 保存用户信息
*
* @param user
*/
public void insert(User user) {
// 生成 id
Long id = generateld();
// 给 user 对象 id 属性赋值
user.setId(id);
// 保存
users.add(user);
}
/**
* 根据 id 查询用户信息
*
* @param id
* @return
*/
public User selectById(Long id) {
// Steam API
User user2 = users.stream().filter(user -> user.getId().equals(id)).findFirst().get();
return user2;
}
/**
* 修改用户信息
* @param user
*/
public void upate(User user) {
for (int i = 0; i < users.size(); i++) {
if(users.get(i).getId().equals(user.getId())) {
users.set(i,user);
return;
}
}
}
/**
* 删除用户信息
* @param id
*/
public void deleteByid(Long id) {
for (int i = 0; i < users.size(); i++) {
if(users.get(i).getId().equals(id)) {
// 移除
users.remove(i);
return;
}
}
}
}
最后:
“在这个最后的篇章中,我要表达我对每一位读者的感激之情。你们的关注和回复是我创作的动力源泉,我从你们身上吸取了无尽的灵感与勇气。我会将你们的鼓励留在心底,继续在其他的领域奋斗。感谢你们,我们总会在某个时刻再次相遇。”