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

本文涉及的产品
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS PostgreSQL,集群系列 2核4GB
简介: 项目介绍  在前两篇博客: 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), 欢迎大家关注哦~~

相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
9天前
|
JavaScript Java 关系型数据库
毕设项目&课程设计&毕设项目:基于springboot+vue实现的在线考试系统(含教程&源码&数据库数据)
本文介绍了一个基于Spring Boot和Vue.js实现的在线考试系统。随着在线教育的发展,在线考试系统的重要性日益凸显。该系统不仅能提高教学效率,减轻教师负担,还为学生提供了灵活便捷的考试方式。技术栈包括Spring Boot、Vue.js、Element-UI等,支持多种角色登录,具备考试管理、题库管理、成绩查询等功能。系统采用前后端分离架构,具备高性能和扩展性,未来可进一步优化并引入AI技术提升智能化水平。
毕设项目&课程设计&毕设项目:基于springboot+vue实现的在线考试系统(含教程&源码&数据库数据)
|
11天前
|
Java 关系型数据库 MySQL
毕设项目&课程设计&毕设项目:springboot+jsp实现的房屋租租赁系统(含教程&源码&数据库数据)
本文介绍了一款基于Spring Boot和JSP技术的房屋租赁系统,旨在通过自动化和信息化手段提升房屋管理效率,优化租户体验。系统采用JDK 1.8、Maven 3.6、MySQL 8.0、JSP、Layui和Spring Boot 2.0等技术栈,实现了高效的房源管理和便捷的租户服务。通过该系统,房东可以轻松管理房源,租户可以快速找到合适的住所,双方都能享受数字化带来的便利。未来,系统将持续优化升级,提供更多完善的服务。
毕设项目&课程设计&毕设项目:springboot+jsp实现的房屋租租赁系统(含教程&源码&数据库数据)
|
3天前
|
Java 关系型数据库 数据库连接
SpringBoot项目使用yml文件链接数据库异常
【10月更文挑战第3天】Spring Boot项目中数据库连接问题可能源于配置错误或依赖缺失。YAML配置文件的格式不正确,如缩进错误,会导致解析失败;而数据库驱动不匹配、连接字符串或认证信息错误同样引发连接异常。解决方法包括检查并修正YAML格式,确认配置属性无误,以及添加正确的数据库驱动依赖。利用日志记录和异常信息分析可辅助问题排查。
22 10
|
1天前
|
Java 关系型数据库 MySQL
SpringBoot项目使用yml文件链接数据库异常
【10月更文挑战第4天】本文分析了Spring Boot应用在连接数据库时可能遇到的问题及其解决方案。主要从四个方面探讨:配置文件格式错误、依赖缺失或版本不兼容、数据库服务问题、配置属性未正确注入。针对这些问题,提供了详细的检查方法和调试技巧,如检查YAML格式、验证依赖版本、确认数据库服务状态及用户权限,并通过日志和断点调试定位问题。
|
1天前
|
缓存 NoSQL Java
Springboot自定义注解+aop实现redis自动清除缓存功能
通过上述步骤,我们不仅实现了一个高度灵活的缓存管理机制,还保证了代码的整洁与可维护性。自定义注解与AOP的结合,让缓存清除逻辑与业务逻辑分离,便于未来的扩展和修改。这种设计模式非常适合需要频繁更新缓存的应用场景,大大提高了开发效率和系统的响应速度。
8 2
|
2月前
|
JavaScript Java 关系型数据库
毕设项目&课程设计&毕设项目:基于springboot+vue实现的前后端分离的选课管理系统(含教程&源码&数据库数据)
本文介绍了一个基于Spring Boot和Vue.js技术栈的高校选课管理系统的设计与实现。该系统采用前后端分离架构,旨在提高选课效率、优化资源分配及提升用户体验。技术栈包括:后端Spring Boot 2.0、前端Vue 2.0、数据库MySQL 8.0、开发环境JDK 1.8和Maven 3.6等。系统功能覆盖登录、学生信息管理、选课管理、成绩查询等多个方面,并针对学生、教师和管理员提供了不同的操作界面。系统采用了响应式设计,支持多设备访问,并通过Element UI增强了界面的友好性和交互性。
毕设项目&课程设计&毕设项目:基于springboot+vue实现的前后端分离的选课管理系统(含教程&源码&数据库数据)
|
2月前
|
安全 Java 关系型数据库
毕设项目&课程设计&毕设项目:基于springboot+jsp实现的健身房管理系统(含教程&源码&数据库数据)
本文介绍了一款基于Spring Boot和JSP技术实现的健身房管理系统。随着健康生活观念的普及,健身房成为日常锻炼的重要场所,高效管理会员信息、课程安排等变得尤为重要。该系统旨在通过简洁的操作界面帮助管理者轻松处理日常运营挑战。技术栈包括:JDK 1.8、Maven 3.6、MySQL 8.0、JSP、Shiro、Spring Boot 2.0等。系统功能覆盖登录、会员管理(如会员列表、充值管理)、教练管理、课程管理、器材管理、物品遗失管理、商品管理及信息统计等多方面。
|
2月前
|
JavaScript Java 关系型数据库
毕设项目&课程设计&毕设项目:基于springboot+vue实现的前后端分离的考试管理系统(含教程&源码&数据库数据)
在数字化时代背景下,本文详细介绍了如何使用Spring Boot框架结合Vue.js技术栈,实现一个前后端分离的考试管理系统。该系统旨在提升考试管理效率,优化用户体验,确保数据安全及可维护性。技术选型包括:Spring Boot 2.0、Vue.js 2.0、Node.js 12.14.0、MySQL 8.0、Element-UI等。系统功能涵盖登录注册、学员考试(包括查看试卷、答题、成绩查询等)、管理员功能(题库管理、试题管理、试卷管理、系统设置等)。
毕设项目&课程设计&毕设项目:基于springboot+vue实现的前后端分离的考试管理系统(含教程&源码&数据库数据)
|
2月前
|
JavaScript Java Maven
毕设项目&课程设计&毕设项目:springboot+vue实现的在线求职管理平台(含教程&源码&数据库数据)
本文介绍了一款基于Spring Boot和Vue.js实现的在线求职平台。该平台采用了前后端分离的架构,使用Spring Boot作为后端服务
毕设项目&课程设计&毕设项目:springboot+vue实现的在线求职管理平台(含教程&源码&数据库数据)
下一篇
无影云桌面