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


    目录

    (一)连接MySql

    (二)创建实体模型

    (三)创建Repository接口

    (四)创建Controller类

      (五)运行AccessingDataMysqlApplication

    (六)HTML页面设置


    参考SpringBoot官网教程:

    1.Validating Form Input

    2.Handling Form Submission

    3.Accessing data with MySQL

    (一)连接MySql

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

    1. ---------连接数据库----------
    2. <dependency>
    3. <groupId>mysql</groupId>
    4. <artifactId>mysql-connector-java</artifactId>
    5. <version>8.0.12</version>
    6. </dependency>
    7. -------用于启用JPA和Hibernate,实现数据的持久化-------
    8. <dependency>
    9. <groupId>org.springframework.boot</groupId>
    10. <artifactId>spring-boot-starter-data-jpa</artifactId>
    11. </dependency>
    12. -----------启用web应用程序----------
    13. <dependency>
    14. <groupId>org.springframework.boot</groupId>
    15. <artifactId>spring-boot-starter-web</artifactId>
    16. </dependency>
    17. --------用于构建交互的WEB应用程序-------
    18. <dependency>
    19. <groupId>org.springframework.boot</groupId>
    20. <artifactId>spring-boot-starter-thymeleaf</artifactId>
    21. </dependency>
    22. -------启用校验功能----------
    23. <dependency>
    24. <groupId>org.springframework.boot</groupId>
    25. <artifactId>spring-boot-starter-validation</artifactId>
    26. <version>3.1.5</version>
    27. </dependency>

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

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

    也可以添加application.yml:

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

    1. spring:
    2. datasource:
    3. driver-class-name: com.mysql.jdbc.Driver
    4. url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&useSSL=false
    5. username: root
    6. password: 123456ab

    (二)创建实体模型

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

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

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

    1. package com.example.accessingdatamysql;
    2. import jakarta.persistence.Entity;
    3. import jakarta.persistence.GeneratedValue;
    4. import jakarta.persistence.GenerationType;
    5. import jakarta.persistence.Id;
    6. import jakarta.persistence.SequenceGenerator;
    7. import jakarta.validation.constraints.NotEmpty;
    8. import jakarta.validation.constraints.Email;
    9. import jakarta.validation.constraints.NotNull;
    10. import jakarta.validation.constraints.Size;
    11. @Entity // This tells Hibernate to make a table out of this class
    12. public class User {
    13. @Id
    14. //指定序列生成器,序列生成器的名称为"user_seq"
    15. @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_seq")
    16. //每次增长值为1
    17. @SequenceGenerator(name = "user_seq", sequenceName = "user_seq", allocationSize = 1)
    18. private Integer id;
    19. @NotNull(message = "姓名不能为空")
    20. @Size(min = 2, max = 30, message = "姓名长度必须在2-30之间")
    21. private String name;
    22. @Email
    23. @NotEmpty(message = "邮箱不能为空")
    24. private String email;
    25. public Integer getId() {
    26. return id;
    27. }
    28. public void setId(Integer id) {
    29. this.id = id;
    30. }
    31. public String getName() {
    32. return name;
    33. }
    34. public void setName(String name) {
    35. this.name = name;
    36. }
    37. public String getEmail() {
    38. return email;
    39. }
    40. public void setEmail(String email) {
    41. this.email = email;
    42. }
    43. public String toString() {
    44. return "User(id:" + this.id + ",name:" + this.name + ",email:" + this.email + ")";
    45. }
    46. }

    (三)创建Repository接口

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

    1. package com.example.accessingdatamysql;
    2. import org.springframework.data.repository.CrudRepository;
    3. // import com.example.accessingdatamysql.User;
    4. // This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository
    5. // CRUD refers Create, Read, Update, Delete
    6. //使用Iterable,可以根据条件来查询匹配的用户,并获取到一个包含所有符合条件的迭代的用户列表。
    7. public interface UserRepository extends CrudRepository<User, Integer> {
    8. //根据姓名查询用户
    9. Iterable<User> findByName(String name);
    10. //根据邮箱查询用户
    11. Iterable<User> findByEmail(String email);
    12. //根据邮箱和姓名查询用户
    13. Iterable<User> findByNameAndEmail(String email,String name);
    14. }

    (四)创建Controller类

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

    1. package com.example.accessingdatamysql;
    2. import org.springframework.beans.factory.annotation.Autowired;
    3. import org.springframework.stereotype.Controller;
    4. import org.springframework.ui.Model;
    5. import org.springframework.validation.BindingResult;
    6. import org.springframework.validation.annotation.Validated;
    7. import org.springframework.web.bind.annotation.GetMapping;
    8. import org.springframework.web.bind.annotation.ModelAttribute;
    9. import org.springframework.web.bind.annotation.PathVariable;
    10. import org.springframework.web.bind.annotation.PostMapping;
    11. import org.springframework.web.bind.annotation.RequestParam;
    12. import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
    13. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    14. import jakarta.validation.Valid;
    15. @Controller
    16. @Validated
    17. public class WebController implements WebMvcConfigurer {
    18. @Autowired
    19. private UserRepository userRepository;
    20. @Override
    21. public void addViewControllers(ViewControllerRegistry registry) {
    22. registry.addViewController("/results").setViewName("results");
    23. }
    24. @GetMapping("/form")
    25. public String showForm(Model model) {
    26. model.addAttribute("user", new User());
    27. return "form";
    28. }
    29. @PostMapping("/")
    30. public String submintForm(@Valid @ModelAttribute("user") User user, BindingResult bindingResult) {
    31. if (bindingResult.hasErrors()) {
    32. return "form";
    33. }
    34. userRepository.save(user);
    35. return "redirect:/list";
    36. }
    37. @GetMapping("/list")
    38. public String showList(Model model) {
    39. model.addAttribute("userList", userRepository.findAll());
    40. return "list";
    41. }
    42. @GetMapping(path = "/deleteAll")
    43. public String deleteAllUsers(Model model) {
    44. userRepository.deleteAll();
    45. Iterable<User> userList = userRepository.findAll();
    46. model.addAttribute("userList", userList);
    47. return "redirect:/list";
    48. }
    49. @GetMapping(path = "/delete/{id}")
    50. public String deleteUser(@PathVariable("id") Integer id, Model model) {
    51. userRepository.deleteById(id);
    52. Iterable<User> userList = userRepository.findAll();
    53. model.addAttribute("userList", userList);
    54. return "redirect:/list"; // 返回list.html模板
    55. }
    56. @GetMapping(path = "/edit/{id}")
    57. public String updateUser(@PathVariable("id") Integer id, Model model) {
    58. User user = userRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("Invalid user ID"));
    59. model.addAttribute("user", user);
    60. return "edit";
    61. }
    62. @PostMapping(path = "/update")
    63. public String update(@Valid User user, Model model) {
    64. userRepository.save(user);
    65. Iterable<User> userList = userRepository.findAll();
    66. model.addAttribute("userList", userList);
    67. return "list";
    68. }
    69. @GetMapping("/find")
    70. public String findUserByNameAndEmail(@RequestParam("name") String name,
    71. @RequestParam("email") String email, Model model) {
    72. Iterable<User> userlist;
    73. if (!name.isEmpty() && !email.isEmpty()) {
    74. // 根据姓名和邮箱查询用户
    75. userlist = userRepository.findByNameAndEmail(name, email);
    76. } else if (!name.isEmpty()) {
    77. // 根据姓名查询用户
    78. userlist = userRepository.findByName(name);
    79. } else if (!email.isEmpty()) {
    80. // 根据邮箱查询用户
    81. userlist = userRepository.findByEmail(email);
    82. } else {
    83. // 返回所有用户
    84. userlist = userRepository.findAll();
    85. }
    86. model.addAttribute("userlist", userlist);
    87. return "check";
    88. }
    89. }

    这里的注释

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

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

    1. @RestController
    2. @RequestMapping("/user")
    3. public class UserController {
    4. @PostMapping
    5. public User create (@Valid @RequestBody User user) {
    6. System.out.println(user.getId());
    7. System.out.println(user.getUsername());
    8. System.out.println(user.getPassword());
    9. user.setId("1");
    10. return user;
    11. }
    12. }
    13. public class User {
    14. private String id;
    15. @NotBlank(message = "密码不能为空")
    16. private String password;
    17. }

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

    1. //url参数中的name必须要和@RequestParam("name")一致
    2. @RequestMapping("show16")
    3. public ModelAndView test16(@RequestParam("name")String name){
    4. ModelAndView mv = new ModelAndView();
    5. mv.setViewName("hello");
    6. mv.addObject("msg", "接收普通的请求参数:" + name);
    7. return mv;
    8. }

    得到结果

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

    页面:

    接收普通的请求参数:cc

    (五)运行AccessingDataMysqlApplication
    1. package com.example.accessingdatamysql;
    2. import org.springframework.boot.SpringApplication;
    3. import org.springframework.boot.autoconfigure.SpringBootApplication;
    4. @SpringBootApplication
    5. public class AccessingDataMysqlApplication {
    6. public static void main(String[] args) {
    7. SpringApplication.run(AccessingDataMysqlApplication.class, args);
    8. }
    9. }

    (六)HTML页面设置

    check.html

    1. <!DOCTYPE html>
    2. <html xmlns:th="http://www.thymeleaf.org">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>Check User List</title>
    6. <style>
    7. body {
    8. display: flex;
    9. align-items: stretch;
    10. height: 100vh;
    11. background-color: #f2f2f2;
    12. justify-content: space-between;
    13. flex-wrap: wrap;
    14. flex-direction: column;
    15. align-content: center;
    16. }
    17. table {
    18. width: 600px;
    19. margin-top: 20px;
    20. border-collapse: collapse;
    21. background-color: #fff;
    22. box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    23. }
    24. table th,
    25. table td {
    26. padding: 10px;
    27. text-align: center;
    28. border: 1px solid #ccc;
    29. }
    30. table th {
    31. background-color: #f2f2f2;
    32. }
    33. a {
    34. display: block;
    35. text-align: center;
    36. margin-top: 20px;
    37. text-decoration: none;
    38. color: #4CAF50;
    39. font-weight: bold;
    40. }
    41. a:hover {
    42. color: #45a049;
    43. }
    44. .btn-edit,
    45. .btn-delete {
    46. display: inline-block;
    47. padding: 5px 10px;
    48. border: none;
    49. background-color: #4CAF50;
    50. color: white;
    51. text-decoration: none;
    52. cursor: pointer;
    53. }
    54. .btn-edit:hover,
    55. .btn-delete:hover {
    56. background-color: #45a049;
    57. }
    58. </style>
    59. </head>
    60. <body>
    61. <h1 style="text-align: center; margin-bottom: 20px;">Check User List</h1>
    62. <form th:action="@{/find}" method="get" style="text-align: center;">
    63. <input type="text" name="name" placeholder="姓名">
    64. <input type="text" name="email" placeholder="邮箱">
    65. <button type="submit">查询</button>
    66. </form>
    67. <table>
    68. <tr>
    69. <th>Name</th>
    70. <th>Email</th>
    71. <th>操作</th>
    72. </tr>
    73. <tr th:each="user : ${userlist}">
    74. <td th:text="${user.name}"></td>
    75. <td th:text="${user.email}"></td>
    76. <td>
    77. <a th:href="@{'/edit/' + ${user.id}}" class="btn-edit">编辑</a>
    78. <a th:href="@{'/delete/' + ${user.id}}" class="btn-delete">删除</a>
    79. </td>
    80. </tr>
    81. </table>
    82. <a href="/form" style="text-align: center; margin-top: 20px; display: block;">添加新信息</a>
    83. </body>
    84. </html>

    edit.html

    1. <!DOCTYPE html>
    2. <html xmlns:th="http://www.thymeleaf.org">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>Edit User</title>
    6. <style>
    7. body {
    8. display: flex;
    9. align-items: center;
    10. height: 100vh;
    11. background-color: #f2f2f2;
    12. flex-direction: column;
    13. flex-wrap: wrap;
    14. align-content: center;
    15. justify-content: center;
    16. }
    17. form {
    18. width: 400px;
    19. padding: 20px;
    20. background-color: #fff;
    21. box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    22. text-align: center;
    23. }
    24. label {
    25. display: block;
    26. margin-bottom: 10px;
    27. font-weight: bold;
    28. }
    29. input {
    30. width: 100%;
    31. padding: 8px;
    32. margin-bottom: 20px;
    33. border: 1px solid #ccc;
    34. border-radius: 4px;
    35. box-sizing: border-box;
    36. }
    37. button {
    38. padding: 10px 20px;
    39. border: none;
    40. background-color: #4CAF50;
    41. color: white;
    42. text-decoration: none;
    43. cursor: pointer;
    44. }
    45. button:hover {
    46. background-color: #45a049;
    47. }
    48. a {
    49. display: block;
    50. margin-top: 20px;
    51. text-align: center;
    52. text-decoration: none;
    53. color: #4CAF50;
    54. font-weight: bold;
    55. }
    56. a:hover {
    57. color: #45a049;
    58. }
    59. </style>
    60. </head>
    61. <body>
    62. <h1>编辑信息</h1>
    63. <form th:action="@{/update}" method="post">
    64. <input type="hidden" th:name="id" th:value="${id}" />
    65. <label for="name">Name:</label>
    66. <input type="text" id="name" name="name" th:value="${name}" />
    67. <label for="email">Email:</label>
    68. <input type="email" id="email" name="email" th:value="${email}" />
    69. <button type="submit">保存</button>
    70. </form>
    71. <a href="/list">返回列表</a>
    72. </body>
    73. </html>

    form.html

    1. <!DOCTYPE html>
    2. <html xmlns:th="http://www.thymeleaf.org">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>Form</title>
    6. <style>
    7. body {
    8. display: flex;
    9. justify-content: center;
    10. align-items: center;
    11. height: 100vh;
    12. background-color: #f2f2f2;
    13. }
    14. .form-container {
    15. width: 400px;
    16. padding: 20px;
    17. background-color: #fff;
    18. border-radius: 5px;
    19. box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    20. }
    21. .form-container h1 {
    22. text-align: center;
    23. margin-bottom: 20px;
    24. }
    25. .form-container label {
    26. display: block;
    27. margin-bottom: 10px;
    28. }
    29. .form-container input[type="text"],
    30. .form-container input[type="email"] {
    31. width: 100%;
    32. padding: 10px;
    33. border: 1px solid #ccc;
    34. border-radius: 5px;
    35. }
    36. .form-container button[type="submit"] {
    37. display: block;
    38. width: 100%;
    39. padding: 10px;
    40. margin-top: 20px;
    41. background-color: #4CAF50;
    42. color: #fff;
    43. border: none;
    44. border-radius: 5px;
    45. cursor: pointer;
    46. }
    47. .form-container button[type="submit"]:hover {
    48. background-color: #45a049;
    49. }
    50. .form-container button[type="reset"] {
    51. display: block;
    52. width: 100%;
    53. padding: 10px;
    54. margin-top: 20px;
    55. background-color: #4CAF50;
    56. color: #fff;
    57. border: none;
    58. border-radius: 5px;
    59. cursor: pointer;
    60. }
    61. .form-container button[type="reset"]:hover {
    62. background-color: #45a049;
    63. }
    64. .form-container button[type="delete"] {
    65. display: block;
    66. width: 100%;
    67. padding: 10px;
    68. margin-top: 20px;
    69. background-color: #4CAF50;
    70. color: #fff;
    71. border: none;
    72. border-radius: 5px;
    73. cursor: pointer;
    74. }
    75. .form-container button[type="delete"]:hover {
    76. background-color: #45a049;
    77. }
    78. .form-container span {
    79. color: red;
    80. font-size: 12px;
    81. margin-top: 5px;
    82. }
    83. </style>
    84. </head>
    85. <body>
    86. <div class="form-container">
    87. <h1>表格</h1>
    88. <form action="#" th:action="@{/}" th:object="${user}" method="post">
    89. <div>
    90. <label for="name">Name:</label>
    91. <input type="text" id="name" th:field="*{name}" required>
    92. <span th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name Error</span>
    93. </div>
    94. <div>
    95. <label for="email">Email:</label>
    96. <input type="text" id="email" th:field="*{email}" required>
    97. <span th:if="${#fields.hasErrors('email')}" th:errors="*{email}">Email Error</span>
    98. </div>
    99. <div>
    100. <button type="submit">Submit</button>
    101. <button type="reset">Reset</button>
    102. <button type="delete">Delete</button>
    103. </div>
    104. </form>
    105. </div>
    106. </body>
    107. </html>

    list.html

    1. <!DOCTYPE html>
    2. <html xmlns:th="http://www.thymeleaf.org">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>List</title>
    6. <style>
    7. body {
    8. display: flex;
    9. align-items: stretch;
    10. height: 100vh;
    11. background-color: #f2f2f2;
    12. justify-content: space-between;
    13. flex-wrap: wrap;
    14. flex-direction: column;
    15. align-content: center;
    16. }
    17. table {
    18. width: 600px;
    19. margin-top: 20px;
    20. border-collapse: collapse;
    21. background-color: #fff;
    22. box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    23. }
    24. table th,
    25. table td {
    26. padding: 10px;
    27. text-align: center;
    28. border: 1px solid #ccc;
    29. }
    30. table th {
    31. background-color: #f2f2f2;
    32. }
    33. a {
    34. display: block;
    35. text-align: center;
    36. margin-top: 20px;
    37. text-decoration: none;
    38. color: #4CAF50;
    39. font-weight: bold;
    40. }
    41. a:hover {
    42. color: #45a049;
    43. }
    44. .btn-edit,
    45. .btn-delete {
    46. display: inline-block;
    47. padding: 5px 10px;
    48. border: none;
    49. background-color: #4CAF50;
    50. color: white;
    51. text-decoration: none;
    52. cursor: pointer;
    53. }
    54. .btn-edit:hover,
    55. .btn-delete:hover {
    56. background-color: #45a049;
    57. }
    58. .btn-delete-all {
    59. display: block;
    60. text-align: center;
    61. margin-top: 20px;
    62. text-decoration: none;
    63. color: #f44336;
    64. font-weight: bold;
    65. }
    66. .btn-delete-all:hover {
    67. color: #d32f2f;
    68. }
    69. </style>
    70. </head>
    71. <body>
    72. <h1 style="text-align: center; margin-bottom: 20px;">信息系统</h1>
    73. <form th:action="@{/find}" method="get" style="text-align: center;">
    74. <input type="text" name="name" placeholder="姓名">
    75. <input type="text" name="email" placeholder="邮箱">
    76. <button type="submit">查询</button>
    77. </form>
    78. <table>
    79. <tr>
    80. <th>Name</th>
    81. <th>Email</th>
    82. <th>操作</th>
    83. </tr>
    84. <tr th:each="user : ${userList}">
    85. <td th:text="${user.name}"></td>
    86. <td th:text="${user.email}"></td>
    87. <td>
    88. <a th:href="@{'/edit/' + ${user.id}}" class="btn-edit">编辑</a>
    89. <a th:href="@{'/delete/' + ${user.id}}" class="btn-delete">删除</a>
    90. </td>
    91. </tr>
    92. </table>
    93. <a href="/form" style="text-align: center; margin-top: 20px; display: block;">添加新信息</a>
    94. <a href="/deleteAll" class="btn-delete-all">删除全部用户信息</a>
    95. </body>
    96. </html>

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

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

  • 相关阅读:
    Java数据结构——二叉搜索树
    1024程序员节——我是猿,我为自己带盐
    Java并发编程的艺术笔记-Java并发编程基础
    在Navicat工具中如何利用SQL语句和可视化界面这两种方法来创建数据表
    微信公众号基本配置之服务器配置
    Structured Streaming
    命令执行漏洞——系统命令执行
    企业需要什么样的数字化官网,网站建设模式及成功关键因素
    【库函数】复习小结
    红外相机:巨哥红外MAG32产品介绍
  • 原文地址:https://blog.csdn.net/weixin_69884785/article/details/134334814