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

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
云数据库 RDS PostgreSQL,高可用系列 2核4GB
简介: SpringBoot-----从前端更新数据到MySql数据库

参考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 实现框架将这个类映射为数据库中的表

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

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>
相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
目录
相关文章
|
存储 前端开发 安全
前端如何存储数据:Cookie、LocalStorage 与 SessionStorage 全面解析
本文全面解析前端三种数据存储方式:Cookie、LocalStorage与SessionStorage。涵盖其定义、使用方法、生命周期、优缺点及典型应用场景,帮助开发者根据登录状态、用户偏好、会话控制等需求,选择合适的存储方案,提升Web应用的性能与安全性。(238字)
414 0
|
4月前
|
存储 JSON 关系型数据库
【干货满满】解密 API 数据解析:从 JSON 到数据库存储的完整流程
本文详解电商API开发中JSON数据解析与数据库存储的全流程,涵盖数据提取、清洗、转换及优化策略,结合Python实战代码与主流数据库方案,助开发者构建高效、可靠的数据处理管道。
|
6月前
|
缓存 NoSQL 关系型数据库
美团面试:MySQL有1000w数据,redis只存20w的数据,如何做 缓存 设计?
美团面试:MySQL有1000w数据,redis只存20w的数据,如何做 缓存 设计?
美团面试:MySQL有1000w数据,redis只存20w的数据,如何做 缓存 设计?
|
4月前
|
SQL 人工智能 关系型数据库
如何实现MySQL百万级数据的查询?
本文探讨了在MySQL中对百万级数据进行排序分页查询的优化策略。面对五百万条数据,传统的浅分页和深分页查询效率较低,尤其深分页因偏移量大导致性能显著下降。通过为排序字段添加索引、使用联合索引、手动回表等方法,有效提升了查询速度。最终建议根据业务需求选择合适方案:浅分页可加单列索引,深分页推荐联合索引或子查询优化,同时结合前端传递最后一条数据ID的方式实现高效翻页。
254 0
|
2月前
|
数据采集 关系型数据库 MySQL
python爬取数据存入数据库
Python爬虫结合Scrapy与SQLAlchemy,实现高效数据采集并存入MySQL/PostgreSQL/SQLite。通过ORM映射、连接池优化与批量提交,支持百万级数据高速写入,具备良好的可扩展性与稳定性。
|
6月前
|
JavaScript 前端开发 Java
制造业ERP源码,工厂ERP管理系统,前端框架:Vue,后端框架:SpringBoot
这是一套基于SpringBoot+Vue技术栈开发的ERP企业管理系统,采用Java语言与vscode工具。系统涵盖采购/销售、出入库、生产、品质管理等功能,整合客户与供应商数据,支持在线协同和业务全流程管控。同时提供主数据管理、权限控制、工作流审批、报表自定义及打印、在线报表开发和自定义表单功能,助力企业实现高效自动化管理,并通过UniAPP实现移动端支持,满足多场景应用需求。
614 1
|
2月前
|
人工智能 Java 关系型数据库
使用数据连接池进行数据库操作
使用数据连接池进行数据库操作
99 11
|
3月前
|
存储 数据管理 数据库
数据字典是什么?和数据库、数据仓库有什么关系?
在数据处理中,你是否常困惑于字段含义、指标计算或数据来源?数据字典正是解答这些问题的关键工具,它清晰定义数据的名称、类型、来源、计算方式等,服务于开发者、分析师和数据管理者。本文详解数据字典的定义、组成及其与数据库、数据仓库的关系,助你夯实数据基础。
数据字典是什么?和数据库、数据仓库有什么关系?
|
3月前
|
存储 关系型数据库 MySQL
在CentOS 8.x上安装Percona Xtrabackup工具备份MySQL数据步骤。
以上就是在CentOS8.x上通过Perconaxtabbackup工具对Mysql进行高效率、高可靠性、无锁定影响地实现在线快速全量及增加式数据库资料保存与恢复流程。通过以上流程可以有效地将Mysql相关资料按需求完成定期或不定期地保存与灾难恢复需求。
312 10

热门文章

最新文章

推荐镜像

更多