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

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介: 项目介绍  在前两篇博客: 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), 欢迎大家关注哦~~

相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
16天前
|
存储 监控 关系型数据库
轻松入门Mysql:MySQL性能优化与监控,解锁进销存系统的潜力(23)
轻松入门Mysql:MySQL性能优化与监控,解锁进销存系统的潜力(23)
|
16天前
|
SQL 数据可视化 关系型数据库
轻松入门MySQL:深入探究MySQL的ER模型,数据库设计的利器与挑战(22)
轻松入门MySQL:深入探究MySQL的ER模型,数据库设计的利器与挑战(22)
|
16天前
|
存储 关系型数据库 MySQL
轻松入门MySQL:数据库设计之范式规范,优化企业管理系统效率(21)
轻松入门MySQL:数据库设计之范式规范,优化企业管理系统效率(21)
|
16天前
|
存储 关系型数据库 MySQL
轻松入门MySQL:揭秘MySQL游标,数据处理的神秘利器(16)
轻松入门MySQL:揭秘MySQL游标,数据处理的神秘利器(16)
|
16天前
|
存储 SQL 关系型数据库
轻松入门MySQL:加速进销存!利用MySQL存储过程轻松优化每日销售统计(15)
轻松入门MySQL:加速进销存!利用MySQL存储过程轻松优化每日销售统计(15)
|
12天前
|
存储 关系型数据库 MySQL
MySQL基础入门:数据库操作全攻略
MySQL基础入门:数据库操作全攻略
44 0
|
10天前
|
前端开发 Java 数据库连接
Spring系列文章1:Spring入门程序
Spring系列文章1:Spring入门程序
|
1天前
|
Java 关系型数据库 MySQL
一套java+ spring boot与vue+ mysql技术开发的UWB高精度工厂人员定位全套系统源码有应用案例
UWB (ULTRA WIDE BAND, UWB) 技术是一种无线载波通讯技术,它不采用正弦载波,而是利用纳秒级的非正弦波窄脉冲传输数据,因此其所占的频谱范围很宽。一套UWB精确定位系统,最高定位精度可达10cm,具有高精度,高动态,高容量,低功耗的应用。
一套java+ spring boot与vue+ mysql技术开发的UWB高精度工厂人员定位全套系统源码有应用案例
|
7天前
|
XML Java 数据格式
从入门到精通:Spring基础注解的全面解析
从入门到精通:Spring基础注解的全面解析
26 2
从入门到精通:Spring基础注解的全面解析
|
10天前
|
存储 关系型数据库 MySQL
【mybatis-plus】Springboot+AOP+自定义注解实现多数据源操作(数据源信息存在数据库)
【mybatis-plus】Springboot+AOP+自定义注解实现多数据源操作(数据源信息存在数据库)