SpringBoot-----从前端更新数据到MySql数据库

目录

(一)连接MySql

(二)创建实体模型

(三)创建Repository接口

(四)创建Controller类

(五)运行AccessingDataMysqlApplication

(六)HTML页面设置


参考SpringBoot官网教程:

1.Validating Form Input

2.Handling Form Submission

3.Accessing data with MySQL

(一)连接MySql

在pom.xml中引入以下依赖:

复制代码
---------连接数据库----------		
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<version>8.0.12</version>
</dependency>


-------用于启用JPA和Hibernate,实现数据的持久化-------
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-data-jpa</artifactId>
	</dependency>


-----------启用web应用程序----------
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>


--------用于构建交互的WEB应用程序-------
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-thymeleaf</artifactId>
	</dependency>


-------启用校验功能----------
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-validation</artifactId>
		<version>3.1.5</version>
	</dependency>

在application.properties中添加如下代码,连接数据库

复制代码
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/db_example?useSSL=false&serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456ab
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#spring.jpa.show-sql: true
# spring.thymeleaf.cache=false
# spring.thymeleaf.prefix=classpath:/templates/
# spring.thymeleaf.suffix=.html

也可以添加application.yml:

application.yml 的功能和 application.properties 是一样的,不过因为yml文件是树状结构,写起来有更好的层次感,更易于理解,所以很多人都选择了yml文件。

复制代码
spring:
    datasource:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&useSSL=false
        username: root
        password: 123456ab
(二)创建实体模型

@Entity注解用于将一个类标识为 JPA 实体,它告诉 Hibernate 或其他 JPA 实现框架将这个类映射为数据库中的表

注:想深入学习校验方法及注释的小伙伴可以看看这个:

如何在 Spring/Spring Boot 中优雅地做参数校验?-腾讯云开发者社区-腾讯云 (tencent.com)

复制代码
package com.example.accessingdatamysql;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.SequenceGenerator;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;

@Entity // This tells Hibernate to make a table out of this class
public class User {
	@Id
//指定序列生成器,序列生成器的名称为"user_seq"
	@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_seq")
//每次增长值为1
	@SequenceGenerator(name = "user_seq", sequenceName = "user_seq", allocationSize = 1)
	private Integer id;

	@NotNull(message = "姓名不能为空")
	@Size(min = 2, max = 30, message = "姓名长度必须在2-30之间")
	private String name;

	@Email
	@NotEmpty(message = "邮箱不能为空")
	private String email;

	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 getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String toString() {
		return "User(id:" + this.id + ",name:" + this.name + ",email:" + this.email + ")";
	}
}
(三)创建Repository接口

Repository接口,用于定义数据访问的方法

复制代码
package com.example.accessingdatamysql;

import org.springframework.data.repository.CrudRepository;

// import com.example.accessingdatamysql.User;

// This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository
// CRUD refers Create, Read, Update, Delete

//使用Iterable,可以根据条件来查询匹配的用户,并获取到一个包含所有符合条件的迭代的用户列表。
public interface UserRepository extends CrudRepository<User, Integer> {

//根据姓名查询用户
    Iterable<User> findByName(String name);

//根据邮箱查询用户
    Iterable<User> findByEmail(String email);

//根据邮箱和姓名查询用户
    Iterable<User> findByNameAndEmail(String email,String name);

}
(四)创建Controller类

Controller类通常用于Web应用程序,它接收用户的HTTP请求,调用业务逻辑处理请求,并返回一个包含响应数据的视图。

复制代码
package com.example.accessingdatamysql;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import jakarta.validation.Valid;

@Controller
@Validated
public class WebController implements WebMvcConfigurer {
    @Autowired
    private UserRepository userRepository;

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/results").setViewName("results");
    }

    @GetMapping("/form")
    public String showForm(Model model) {
        model.addAttribute("user", new User());
        return "form";
    }

    @PostMapping("/")
    public String submintForm(@Valid @ModelAttribute("user") User user, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return "form";
        }
        userRepository.save(user);
        return "redirect:/list";
    }

    @GetMapping("/list")
    public String showList(Model model) {
        model.addAttribute("userList", userRepository.findAll());
        return "list";
    }

    @GetMapping(path = "/deleteAll")
    public String deleteAllUsers(Model model) {
        userRepository.deleteAll();
        Iterable<User> userList = userRepository.findAll();
        model.addAttribute("userList", userList);
        return "redirect:/list";
    }

    @GetMapping(path = "/delete/{id}")
    public String deleteUser(@PathVariable("id") Integer id, Model model) {
        userRepository.deleteById(id);
        Iterable<User> userList = userRepository.findAll();
        model.addAttribute("userList", userList);
        return "redirect:/list"; // 返回list.html模板
    }

    @GetMapping(path = "/edit/{id}")
    public String updateUser(@PathVariable("id") Integer id, Model model) {
        User user = userRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("Invalid user ID"));
        model.addAttribute("user", user);
        return "edit";
    }

    @PostMapping(path = "/update")
    public String update(@Valid User user, Model model) {
        userRepository.save(user);
        Iterable<User> userList = userRepository.findAll();
        model.addAttribute("userList", userList);
        return "list";
    }

    @GetMapping("/find")
    public String findUserByNameAndEmail(@RequestParam("name") String name,
            @RequestParam("email") String email, Model model) {
        Iterable<User> userlist;

        if (!name.isEmpty() && !email.isEmpty()) {
            // 根据姓名和邮箱查询用户
            userlist = userRepository.findByNameAndEmail(name, email);
        } else if (!name.isEmpty()) {
            // 根据姓名查询用户
            userlist = userRepository.findByName(name);
        } else if (!email.isEmpty()) {
            // 根据邮箱查询用户
            userlist = userRepository.findByEmail(email);
        } else {
            // 返回所有用户
            userlist = userRepository.findAll();
        }
        model.addAttribute("userlist", userlist);
        return "check";
    }
}

这里的注释

@Valid:用于验证注释是否符合要求,例如

这里就是检验密码是否为空

复制代码
@RestController
@RequestMapping("/user")
public class UserController {
    @PostMapping
    public User create (@Valid @RequestBody User user) {
        System.out.println(user.getId());
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        user.setId("1");
        return user;
    }
}    

public class User {
    private String id;  
 
    @NotBlank(message = "密码不能为空")
    private String password;
}

**@RequestParam:**将请求参数绑定到你控制器的方法参数上(是springmvc中接收普通参数的注解)

复制代码
//url参数中的name必须要和@RequestParam("name")一致
    @RequestMapping("show16")
    public ModelAndView test16(@RequestParam("name")String name){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("hello");
        mv.addObject("msg", "接收普通的请求参数:" + name);
        return mv;
    }

得到结果

url:localhost:8080/hello/show16?name=cc

页面:

接收普通的请求参数:cc

(五)运行AccessingDataMysqlApplication
复制代码
package com.example.accessingdatamysql;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class AccessingDataMysqlApplication {

	public static void main(String[] args) {
		SpringApplication.run(AccessingDataMysqlApplication.class, args);
	}
}
(六)HTML页面设置

check.html

复制代码
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <title>Check User List</title>
    <style>
        body {
            display: flex;
            align-items: stretch;
            height: 100vh;
            background-color: #f2f2f2;
            justify-content: space-between;
            flex-wrap: wrap;
            flex-direction: column;
            align-content: center;
        }

        table {
            width: 600px;
            margin-top: 20px;
            border-collapse: collapse;
            background-color: #fff;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        table th,
        table td {
            padding: 10px;
            text-align: center;
            border: 1px solid #ccc;
        }

        table th {
            background-color: #f2f2f2;
        }

        a {
            display: block;
            text-align: center;
            margin-top: 20px;
            text-decoration: none;
            color: #4CAF50;
            font-weight: bold;
        }

        a:hover {
            color: #45a049;
        }

        .btn-edit,
        .btn-delete {
            display: inline-block;
            padding: 5px 10px;
            border: none;
            background-color: #4CAF50;
            color: white;
            text-decoration: none;
            cursor: pointer;
        }

        .btn-edit:hover,
        .btn-delete:hover {
            background-color: #45a049;
        }
    </style>
</head>

<body>
    <h1 style="text-align: center; margin-bottom: 20px;">Check User List</h1>
    <form th:action="@{/find}" method="get" style="text-align: center;">
        <input type="text" name="name" placeholder="姓名">
        <input type="text" name="email" placeholder="邮箱">
        <button type="submit">查询</button>
    </form>
    <table>
        <tr>
            <th>Name</th>
            <th>Email</th>
            <th>操作</th>
        </tr>
        <tr th:each="user : ${userlist}">
            <td th:text="${user.name}"></td>
            <td th:text="${user.email}"></td>
            <td>
                <a th:href="@{'/edit/' + ${user.id}}" class="btn-edit">编辑</a>
                <a th:href="@{'/delete/' + ${user.id}}" class="btn-delete">删除</a>
            </td>
        </tr>
    </table>
    <a href="/form" style="text-align: center; margin-top: 20px; display: block;">添加新信息</a>
</body>

</html>

edit.html

复制代码
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <title>Edit User</title>
    <style>
        body {
            display: flex;
            align-items: center;
            height: 100vh;
            background-color: #f2f2f2;
            flex-direction: column;
            flex-wrap: wrap;
            align-content: center;
            justify-content: center;
        }

        form {
            width: 400px;
            padding: 20px;
            background-color: #fff;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            text-align: center;
        }

        label {
            display: block;
            margin-bottom: 10px;
            font-weight: bold;
        }

        input {
            width: 100%;
            padding: 8px;
            margin-bottom: 20px;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-sizing: border-box;
        }

        button {
            padding: 10px 20px;
            border: none;
            background-color: #4CAF50;
            color: white;
            text-decoration: none;
            cursor: pointer;
        }

        button:hover {
            background-color: #45a049;
        }

        a {
            display: block;
            margin-top: 20px;
            text-align: center;
            text-decoration: none;
            color: #4CAF50;
            font-weight: bold;
        }

        a:hover {
            color: #45a049;
        }
    </style>
</head>

<body>
    <h1>编辑信息</h1>

    <form th:action="@{/update}" method="post">
        <input type="hidden" th:name="id" th:value="${id}" />

        <label for="name">Name:</label>
        <input type="text" id="name" name="name" th:value="${name}" />

        <label for="email">Email:</label>
        <input type="email" id="email" name="email" th:value="${email}" />

        <button type="submit">保存</button>
    </form>

    <a href="/list">返回列表</a>
</body>

</html>

form.html

复制代码
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <title>Form</title>
    <style>
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: #f2f2f2;
        }

        .form-container {
            width: 400px;
            padding: 20px;
            background-color: #fff;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        .form-container h1 {
            text-align: center;
            margin-bottom: 20px;
        }

        .form-container label {
            display: block;
            margin-bottom: 10px;
        }

        .form-container input[type="text"],
        .form-container input[type="email"] {
            width: 100%;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
        }

        .form-container button[type="submit"] {
            display: block;
            width: 100%;
            padding: 10px;
            margin-top: 20px;
            background-color: #4CAF50;
            color: #fff;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        .form-container button[type="submit"]:hover {
            background-color: #45a049;
        }

        .form-container button[type="reset"] {
            display: block;
            width: 100%;
            padding: 10px;
            margin-top: 20px;
            background-color: #4CAF50;
            color: #fff;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        .form-container button[type="reset"]:hover {
            background-color: #45a049;
        }

        .form-container button[type="delete"] {
            display: block;
            width: 100%;
            padding: 10px;
            margin-top: 20px;
            background-color: #4CAF50;
            color: #fff;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        .form-container button[type="delete"]:hover {
            background-color: #45a049;
        }

        .form-container span {
            color: red;
            font-size: 12px;
            margin-top: 5px;
        }
    </style>
</head>


<body>
    <div class="form-container">
        <h1>表格</h1>
        <form action="#" th:action="@{/}" th:object="${user}" method="post">
            <div>
                <label for="name">Name:</label>
                <input type="text" id="name" th:field="*{name}" required>
                <span th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name Error</span>
            </div>
            <div>
                <label for="email">Email:</label>
                <input type="text" id="email" th:field="*{email}" required>
                <span th:if="${#fields.hasErrors('email')}" th:errors="*{email}">Email Error</span>
            </div>
            <div>
                <button type="submit">Submit</button>
                <button type="reset">Reset</button>
                <button type="delete">Delete</button>
            </div>
        </form>
    </div>
</body>

</html>

list.html

复制代码
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <title>List</title>
    <style>
        body {
            display: flex;
            align-items: stretch;
            height: 100vh;
            background-color: #f2f2f2;
            justify-content: space-between;
            flex-wrap: wrap;
            flex-direction: column;
            align-content: center;
        }

        table {
            width: 600px;
            margin-top: 20px;
            border-collapse: collapse;
            background-color: #fff;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        table th,
        table td {
            padding: 10px;
            text-align: center;
            border: 1px solid #ccc;
        }

        table th {
            background-color: #f2f2f2;
        }

        a {
            display: block;
            text-align: center;
            margin-top: 20px;
            text-decoration: none;
            color: #4CAF50;
            font-weight: bold;
        }

        a:hover {
            color: #45a049;
        }

        .btn-edit,
        .btn-delete {
            display: inline-block;
            padding: 5px 10px;
            border: none;
            background-color: #4CAF50;
            color: white;
            text-decoration: none;
            cursor: pointer;
        }

        .btn-edit:hover,
        .btn-delete:hover {
            background-color: #45a049;
        }

        .btn-delete-all {
            display: block;
            text-align: center;
            margin-top: 20px;
            text-decoration: none;
            color: #f44336;
            font-weight: bold;
        }

        .btn-delete-all:hover {
            color: #d32f2f;
        }
    </style>
</head>

<body>
    <h1 style="text-align: center; margin-bottom: 20px;">信息系统</h1>
    <form th:action="@{/find}" method="get" style="text-align: center;">
        <input type="text" name="name" placeholder="姓名">
        <input type="text" name="email" placeholder="邮箱">
        <button type="submit">查询</button>
    </form>
    <table>
        <tr>
            <th>Name</th>
            <th>Email</th>
            <th>操作</th>
        </tr>
        <tr th:each="user : ${userList}">
            <td th:text="${user.name}"></td>
            <td th:text="${user.email}"></td>
            <td>
                <a th:href="@{'/edit/' + ${user.id}}" class="btn-edit">编辑</a>
                <a th:href="@{'/delete/' + ${user.id}}" class="btn-delete">删除</a>
            </td>
        </tr>
    </table>
    <a href="/form" style="text-align: center; margin-top: 20px; display: block;">添加新信息</a>
    <a href="/deleteAll" class="btn-delete-all">删除全部用户信息</a>
</body>

</html>

这里的页面可以通过设置css样式表等方式进行改进

**结果:**可以通过前端创建用户,并加入到mysql数据库中

相关推荐
KK溜了溜了41 分钟前
JAVA-springboot log日志
java·spring boot·logback
超级小忍1 小时前
如何配置 MySQL 允许远程连接
数据库·mysql·adb
吹牛不交税1 小时前
sqlsugar WhereIF条件的大于等于和等于查出来的坑
数据库·mysql
Java水解2 小时前
MySQL DQL全面解析:从入门到精通
后端·mysql
我命由我123452 小时前
Spring Boot 项目集成 Redis 问题:RedisTemplate 多余空格问题
java·开发语言·spring boot·redis·后端·java-ee·intellij-idea
面朝大海,春不暖,花不开2 小时前
Spring Boot消息系统开发指南
java·spring boot·后端
hshpy2 小时前
setting up Activiti BPMN Workflow Engine with Spring Boot
数据库·spring boot·后端
jay神2 小时前
基于Springboot的宠物领养系统
java·spring boot·后端·宠物·软件设计与开发
不知几秋3 小时前
Spring Boot
java·前端·spring boot