在前兩篇博客: Spring Boot入門(2)使用MySQL數據庫和Spring Boot入門(3)處理網頁表單中,咱們已經掌握瞭如何在Spring Boot中操做MySQL數據庫以及網頁中的表單。本次分享講結合以上兩篇博客,實現的功能爲:在網頁中提交表單,而且將表單中的數據存入MySQL中。
網頁表單的內容以下圖:css
提交表單數據後,後臺會將數據插入到MySQL中的表格,而且能夠經過頁面來展現插入的全部記錄。整個處理流程和代碼不會很複雜,因此,下一步,咱們就直接進入項目!html
新建formIntoMySQL項目,配置其起步依賴爲Web, Thymeleaf, JPA, MySQL, 該項目的具體結構以下圖所示:
java
其中劃紅線的部分爲須要修改或者新建的文件。
builg.gradle代碼以下:mysql
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實體類,其代碼以下:linux
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,其代碼以下:git
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接口,其代碼以下:github
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代碼保持不變,以下所示:web
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爲初始進去的網頁,其代碼以下:spring
<!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爲提交表單後跳轉後的頁面,其代碼以下:sql
<!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的六條數據,以下圖:
最後咱們去MySQL數據庫中查看,裏面就有咱們剛纔提交的表單數據,以下圖:
對於初次接觸Spring Boot的讀者來講,以上程序顯得有些複雜、難懂,可是,熟能生巧,只要多加練習,必定會慢慢熟悉Spring Boot的開發流程的。固然,這也是筆者告訴本身的,由於,筆者也是一個新手!
本次項目的Github地址爲https://github.com/percent4/f...: 歡迎你們訪問~~ 本次分享終於結束了,接下來還會繼續更新Spring Boot方面的內容,歡迎你們交流~~