Spring Boot入门(4)提交表单并存入MySQL数据库

本文涉及的产品
RDS AI 助手,专业版
RDS MySQL DuckDB 分析主实例,集群系列 4核8GB
RDS DuckDB + QuickBI 企业套餐,8核32GB + QuickBI 专业版
简介: 项目介绍  在前两篇博客: Spring Boot入门(2)使用MySQL数据库和Spring Boot入门(3)处理网页表单中,我们已经掌握了如何在Spring Boot中操作MySQL数据库以及网页中的表单。

项目介绍

  在前两篇博客: Spring Boot入门(2)使用MySQL数据库Spring Boot入门(3)处理网页表单中,我们已经掌握了如何在Spring Boot中操作MySQL数据库以及网页中的表单。本次分享讲结合以上两篇博客,实现的功能为:在网页中提交表单,并且将表单中的数据存入MySQL中。
  网页表单的内容如下图:


网页表单的内容

提交表单数据后,后台会将数据插入到MySQL中的表格,并且可以通过页面来展示插入的所有记录。整个处理流程和代码不会很复杂,所以,下一步,我们就直接进入项目!

程序

  新建formIntoMySQL项目,配置其起步依赖为Web, Thymeleaf, JPA, MySQL, 该项目的具体结构如下图所示:


formIntoMySQL项目结构

其中划红线的部分为需要修改或者新建的文件。
  builg.gradle代码如下:

buildscript {
    ext {
        springBootVersion = '2.0.1.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'com.form'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
}


dependencies {
    // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.0.0.RELEASE'

    // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf', version: '2.0.1.RELEASE'

    // JPA Data (We are going to use Repositories, Entities, Hibernate, etc...)
    compile 'org.springframework.boot:spring-boot-starter-data-jpa'

    // Use MySQL Connector-J
    compile 'mysql:mysql-connector-java'

    // https://mvnrepository.com/artifact/junit/junit
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

请注意Web和Thymeleaf的版本,这与后面网页显示和操作的实现有关。
  在com.form.formIntoMySQL下新建package entity,其中的User.java为表单中的条目的具体实现的Entity实体类,其代码如下:

package com.form.formIntoMySQL.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity // This tells Hibernate to make a table out of this class
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;
    private String name;
    private Integer age;
    private String gender;
    private String email;
    private String city;

    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 Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getEmail() {
        return email;
    }

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

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

}

  在com.form.formIntoMySQL下新建package Controller,这是存放控制器代码的地方,我们的控制器为UserController.java,其代码如下:

package com.form.formIntoMySQL.Controller;

import com.form.formIntoMySQL.entity.User;
import com.form.formIntoMySQL.UserRepository;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.beans.factory.annotation.Autowired;

@Controller
public class UserController {
    @Autowired // This means to get the bean called userRepository
    // Which is auto-generated by Spring, we will use it to handle the data
    private UserRepository userRepository;

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

    @PostMapping("/greeting")
    public String greetingSubmit(@ModelAttribute User user) {

        User newUser = new User();

        newUser.setName(user.getName());
        newUser.setAge(user.getAge());
        newUser.setGender(user.getGender());
        newUser.setEmail(user.getEmail());
        newUser.setCity(user.getCity());
        userRepository.save(user);

        return "result";

    }

    @GetMapping("/all")
    public String getMessage(Model model) {

        Iterable<User> users = userRepository.findAll();

        model.addAttribute("users", users);
        return "all";
    }

}

  接着在com.form.formIntoMySQL下新建UserReposittory.java,来实现CrudRepositoty接口,其代码如下:

package com.form.formIntoMySQL;

import org.springframework.data.repository.CrudRepository;
import com.form.formIntoMySQL.entity.User;

// This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository
// CRUD refers Create, Read, Update, Delete
public interface UserRepository extends CrudRepository<User, Long> {

}

FormIntoMySQLApplication.java代码保持不变,如下所示:

package com.form.formIntoMySQL;

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

@SpringBootApplication
public class FormIntoMySqlApplication {

    public static void main(String[] args) {
        SpringApplication.run(FormIntoMySqlApplication.class, args);
    }
}

  接着需要配置静态资源,即相关的网页,我们项目中的网页采用Thymeleaf视图来实现,其中greeting.html为初始进去的网页,其代码如下:

<!DOCTYPE HTML>

<html xmlns:th="http://www.thymeleaf.org">

<head>
    <title>Form Submission</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
    <center>
        <br><br>
    <h2 style="color:green">Form</h2>
        <br><br>

        <form class="form-horizontal" role="form" action="#" th:action="@{/greeting}" th:object="${user}" method="post">

            <div class="form-group" style="width:300px">
                <label for="name" class="col-sm-2 control-label">Name</label>
                <div class="col-sm-10">
                    <input type="text"  th:field="*{name}" class="form-control" id="name" placeholder="Enter name">
                </div>
            </div>

            <div class="form-group" style="width:300px">
                <label for="age" class="col-sm-2 control-label">Age</label>
                <div class="col-sm-10">
                    <input type="text" th:field="*{age}" class="form-control" id="age" placeholder="Enter age">
                </div>
            </div>

            <div class="form-group" style="width:300px">
                <label for="gender" class="col-sm-2 control-label">Gender</label>
                <div class="col-sm-10">
                    <input type="text" th:field="*{gender}" class="form-control" id="gender" placeholder="Enter gender(M or F)">
                </div>
            </div>

            <div class="form-group" style="width:300px">
                <label for="email" class="col-sm-2 control-label">Email</label>
                <div class="col-sm-10">
                    <input type="text" th:field="*{email}" class="form-control" id="email" placeholder="Enter email">
                </div>
            </div>

            <div class="form-group" style="width:300px">
                <label for="city" class="col-sm-2 control-label">City</label>
                <div class="col-sm-10">
                    <input type="text" th:field="*{city}" class="form-control" id="city" placeholder="Enter city">
                </div>
            </div>

            <div class="form-group">
                <div>
                    <button type="submit" class="btn btn-primary" id="btn">Submit</button>
                    <input type="reset" class="btn btn-warning" value="Reset" />
                </div>
            </div>
        </form>

    </center>

</body>

</html>

result.html为提交表单后跳转后的页面,其代码如下:

<!DOCTYPE HTML>

<html xmlns:th="http://www.thymeleaf.org">

<head>
    <title>Handling Form Submission</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
<center>
    <br><br>
    <h2 style="color:green">Result</h2>
    <br><br>

    <ul class="list-group" style="width:300px">
        <li class="list-group-item" th:text="'Name: ' + ${user.name}"></li>
        <li class="list-group-item" th:text="'Age: ' + ${user.age}"></li>
        <li class="list-group-item" th:text="'Gender: ' + ${user.gender}"></li>
        <li class="list-group-item" th:text="'Email: ' + ${user.email}"></li>
        <li class="list-group-item" th:text="'City: ' + ${user.city}"></li>
    </ul>

    <h4>
        <span class="glyphicon glyphicon-saved"></span>
        Insert into MySQL successfully!
    </h4>

    <a href="/greeting"><button type="button" class="btn btn-primary">Return to home</button></a>
    <a href="/all"><button type="button" class="btn btn-warning">See Records</button></a>

</body>

</html>

all.html为显示MySQL数据库表格user中的所有记录的网页,其具体代码如下:

<!DOCTYPE html>

<html xmlns:th="http://www.thymeleaf.org">

<head>
    <title>User list</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link href="https://cdn.bootcss.com/bootstrap/4.0.0/css/bootstrap.css" rel="stylesheet">
</head>

<body>

<center>
    <br><br>
<h2 style="color:green">All Records in Table user</h2>
    <br><br>

<table class="table table-bordered table table-hover" style="width:800px">
    <tr style="color:red">
        <th>NAME</th>
        <th>Age</th>
        <th>Gender</th>
        <th>Email</th>
        <th>City</th>
    </tr>
    <tr th:each="user : ${users}">
        <td th:text="${user.name}">Jack</td>
        <td th:text="${user.age}">24</td>
        <td th:text="${user.gender}">M</td>
        <td th:text="${user.email}">jack@gmail.com</td>
        <td th:text="${user.city}">New York</td>
    </tr>
</table>

<p>
    <a href="/greeting"><button type="button" class="btn btn-primary">Return to home</button></a>
</p>

</center>
</body>

</html>

  静态资源也配置好了,最后一步就是配置文件application.properties,其代码如下:

spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:33061/test
spring.datasource.username=root
spring.datasource.password=147369

server.port=8000

在这里,我们的数据库表格为新建(create),因为事先不存在user表格,存在后你可以将create操作改为update,这样做能够确保user表格的数据不会被覆盖,而是追加。网页运行端口为8000,MySQL运行端口为33061,这是笔者自己设置过的。

运行

  好不容易写完了程序,下一步当然是愉快地运行以及测试。
  在浏览器端输入http://localhost:8000/greeting ,这是我们程序的入口,提交如下表单:


提交表单

点击Submit按钮,将会跳转到结果显示页面,如下图:


结果显示页面

重复以上操作,将以下5条数据用表单提交:

Name: Alex, Age: 24, Gender: F, Email: alex@baidu.com City:Beijing
Name: Cook, Age: 45, Gender: M, Email: cook@apple.com City:New York
Name: Fork, Age: 31, Gender: F, Email: fork@linux.com City:London
Name: Dan, Age: 17, Gender: M, Email: dan@aliyun.com City:Paris
Name: Hello, Age: 56, Gender: F, Email: hello@happy.com City:Istanbul

在浏览器中输入localhost:8000/all或在greeting页面中点击“See Records”按钮就能够看到刚才我们插入到MySQL数据库test中表格user的六条数据,如下图:


表格user的所有数据

  最后我们去MySQL数据库中查看,里面就有我们刚才提交的表单数据,如下图:


MySQL数据库

结束语

  对于初次接触Spring Boot的读者来说,以上程序显得有些复杂、难懂,但是,熟能生巧,只要多加练习,一定会慢慢熟悉Spring Boot的开发流程的。当然,这也是笔者告诉自己的,因为,笔者也是一个新手!
  本次项目的Github地址为https://github.com/percent4/formIntoMySQL: 欢迎大家访问~~
  本次分享终于结束了,接下来还会继续更新Spring Boot方面的内容,欢迎大家交流~~

注意:本人现已开通两个微信公众号: 用Python做数学(微信号为:python_math)以及轻松学会Python爬虫(微信号为:easy_web_scrape), 欢迎大家关注哦~~

相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
目录
相关文章
|
11月前
|
人工智能 运维 Java
SpringBoot+MySQL实现动态定时任务
这是一个基于Spring Boot的动态定时任务Demo,利用spring-context模块实现任务调度功能。服务启动时会扫描数据库中的任务表,将任务添加到调度器中,并通过固定频率运行的ScheduleUpdater任务动态更新任务状态和Cron表达式。核心功能包括任务的新增、删除与Cron调整,支持通过ScheduledFuture对象控制任务执行。项目依赖Spring Boot 2.2.10.RELEASE,使用MySQL存储任务信息,包含任务基类ITask及具体实现(如FooTask),便于用户扩展运维界面以增强灵活性。
365 10
|
SQL 关系型数据库 MySQL
网安入门之MySQL后端基础
《网安入门之MySQL后端基础》简介: 本文介绍了数据库及MySQL的基础知识,涵盖数据库的概念、结构与操作。数据库是组织化存储数据的集合,通过表、列、行等结构实现高效管理。MySQL作为开源的关系型数据库管理系统,广泛应用于Web开发。文中详细讲解了MySQL的基本操作,如增(INSERT)、删(DELETE)、改(UPDATE)、查(SELECT)等语句的使用方法,并介绍了数据库事务的ACID特性。此外,还探讨了SQL注入攻击的风险及防范措施,强调了预处理语句的重要性。最后,简述了PHP中mysqli扩展的使用方法,包括连接数据库、执行查询和关闭连接等步骤。
|
关系型数据库 MySQL 数据库
MySQL基本操作入门指南
MySQL基本操作入门指南
722 0
|
Java 关系型数据库 MySQL
SpringBoot 通过集成 Flink CDC 来实时追踪 MySql 数据变动
通过详细的步骤和示例代码,您可以在 SpringBoot 项目中成功集成 Flink CDC,并实时追踪 MySQL 数据库的变动。
3329 45
|
监控 Java 关系型数据库
Spring Boot整合MySQL主从集群同步延迟解决方案
本文针对电商系统在Spring Boot+MyBatis架构下的典型问题(如大促时订单状态延迟、库存超卖误判及用户信息更新延迟)提出解决方案。核心内容包括动态数据源路由(强制读主库)、大事务拆分优化以及延迟感知补偿机制,配合MySQL参数调优和监控集成,有效将主从延迟控制在1秒内。实际测试表明,在10万QPS场景下,订单查询延迟显著降低,超卖误判率下降98%。
516 5
|
Java 关系型数据库 MySQL
如何将Spring Boot + MySQL应用程序部署到Pivotal Cloud Foundry (PCF)
如何将Spring Boot + MySQL应用程序部署到Pivotal Cloud Foundry (PCF)
299 5
|
安全 Java 数据安全/隐私保护
如何使用Spring Boot进行表单登录身份验证:从基础到实践
如何使用Spring Boot进行表单登录身份验证:从基础到实践
501 5
|
JavaScript 安全 Java
java版药品不良反应智能监测系统源码,采用SpringBoot、Vue、MySQL技术开发
基于B/S架构,采用Java、SpringBoot、Vue、MySQL等技术自主研发的ADR智能监测系统,适用于三甲医院,支持二次开发。该系统能自动监测全院患者药物不良反应,通过移动端和PC端实时反馈,提升用药安全。系统涵盖规则管理、监测报告、系统管理三大模块,确保精准、高效地处理ADR事件。
611 1
|
SQL 前端开发 关系型数据库
SpringBoot使用mysql查询昨天、今天、过去一周、过去半年、过去一年数据
SpringBoot使用mysql查询昨天、今天、过去一周、过去半年、过去一年数据
469 9
|
分布式计算 关系型数据库 MySQL
SpringBoot项目中mysql字段映射使用JSONObject和JSONArray类型
SpringBoot项目中mysql字段映射使用JSONObject和JSONArray类型 图像处理 光通信 分布式计算 算法语言 信息技术 计算机应用
369 8

热门文章

最新文章

推荐镜像

更多