介紹
在部落格:
Spring Boot入門(4)送出表單并存入MySQL資料庫中,我們利用送出表單往MySQL中插入記錄,這無疑是很友善的。但是,我們沒有對網頁中的表單進行驗證,而表單驗證是網頁表單必不可少的部分。有以下兩種方式對Spring Boot項目中的方法進行驗證:
- 利用JavaScript或者其他JavaScript庫,如jQuery進行表單驗證
- 利用Spring Boot原生方法進行表單驗證
前者需要用到JavaScript方面的知識,對于熟悉JS的讀者來說,這并不是困難的事情,但是表單驗證處理起來比較麻煩,也容易遺漏掉需要驗證的條件。采用Spring Boot原生方法進行表單驗證比較友善,但是需要熟悉Spring Boot方面的知識。
本次分享将利用Spring Boot原生方法進行表單驗證,我們在部落格:
中的Spring Boot項目上加入表單驗證。
介紹程式
我們在原有的Spring Boot項目上進行修改,該Spring Boot項目就是部落格:
中的Spring Boot項目,也可以參看其Github位址:
https://github.com/percent4/formIntoMySQL。該項目的完整結構如下圖:
加入表單驗證需要修改以上三個紅線框内的檔案。
首先是User.java,在代碼中加入表單驗證的限制條件,其代碼如下:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.*;
@Entity // This tells Hibernate to make a table out of this class
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
@NotEmpty
@Size(min=2, max=30)
private String name;
@NotNull
@Min(1)
@Max(200)
private Integer age;
@Pattern(regexp = "[MFmf]")
private String gender;
@NotEmpty
@Email
private String email;
@NotEmpty
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;
}
}
在上述代碼中,@NotEmpty限制字元串不能為空,@Size(min=2, max=30)限制字元串的長度為2到30,@NotNull限制輸入不能為null,@Min(1), @Max(200)限制輸入的數字不能小于1或者大于200,@Pattern(regexp = “[MFmf]”)限制輸入的字元串必須符合正規表達式[MFmf],@Email限制輸入的email位址必須是正确的email位址。
接着我們需要對控制器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.validation.BindingResult;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import javax.validation.Valid;
@Controller
public class UserController implements WebMvcConfigurer{
@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;
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/result").setViewName("result");
}
@GetMapping("/greeting")
public String greetingForm(Model model) {
model.addAttribute("user", new User());
return "greeting";
}
@PostMapping("/greeting")
public String greetingSubmit(@Valid @ModelAttribute User user, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "greeting";
}
else {
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";
}
}
在greetingSubmit()方法中我們加入了表單驗證@Valid,如果出現表單驗證錯誤,則傳回greeting.html頁面,并顯示錯誤資訊,如果表單驗證成功,則傳回result.html頁面。
最後需要對展示驗證表單錯誤資訊的網頁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>
<label style="color:red" th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name Error</label>
</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>
<label style="color:red" th:if="${#fields.hasErrors('age')}" th:errors="*{age}">Age Error</label>
</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>
<label style="color:red" th:if="${#fields.hasErrors('gender')}" th:errors="*{gender}">Gender Error</label>
</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>
<label style="color:red" th:if="${#fields.hasErrors('email')}" th:errors="*{email}">Email Error</label>
</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>
<label style="color:red" th:if="${#fields.hasErrors('city')}" th:errors="*{city}">City Error</label>
</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>
至此,程式以修改完畢。
運作
我們需要對上述程式進行測試,重點在于表單驗證功能。在浏覽器中輸入:
http://localhost:8080/greeting,什麼都不輸入,直接點選Submit按鈕,顯示如下:
再分别驗證其他表單限制條件,如下圖所示:
當表單驗證通過後,我們就能進行result.html結果顯示頁面,如下圖:
結束語
本次分享主要在上篇部落格的基礎上,加入了表單驗證功能,主要的想法是不難的,對于項目結構不熟悉的讀者,可以參考部落格:
或者該項目的Github位址:
.
本次分享主要參考了Spring Boot官網給出的表單驗證的例子:
https://spring.io/guides/gs/validating-form-input/本次程式的Github位址為:
https://github.com/percent4/FormValidation本次分享到此結束,歡迎大家交流~~