驗證表單輸入
阿新 • • 發佈:2019-01-25
你需要什麼
- 大約 15 分鐘
- IntelliJ IDEA或其他編輯器
- JDK 1.8或更高版本
- Maven 3.2+
你會建立什麼
您將構建一個簡單的Spring MVC應用程式,它接受使用者輸入並使用標準驗證註解檢查輸入。您還將看到如何在螢幕上顯示錯誤訊息,以便使用者可以重新輸入有效的輸入。
構建步驟
1、新增maven
依賴。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId >spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 表單驗證模組 -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId >tomcat-embed-el</artifactId>
</dependency>
2、建立一個PersonForm物件
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class PersonForm {
@NotNull
@Size(min=2, max=30)
private String name;
@NotNull
@Min(18)
private Integer age;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String toString() {
return "Person(Name: " + this.name + ", Age: " + this.age + ")";
}
}
@Size(min = 2, max = 30)
只允許長度在2到30個字元之間的名稱@NotNull
將不允許空值@Min(18)
將不允許值小於18
3、建立一個Web Controller
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Controller
public class WebController implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/results").setViewName("results");
}
@GetMapping("/")
public String showForm(PersonForm personForm) {
return "form";
}
@PostMapping("/")
public String checkPersonInfo(@Valid PersonForm personForm, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "form";
}
return "redirect:/results";
}
}
checkPersonFormInfo
方法接受兩個引數:
personForm
物件用@Valid
標記,以收集您即將構建的表單中填寫的屬性。bindingResult
物件,因此您可以測試並檢索驗證錯誤。
4、構建一個HTML表單
<html >
<meta charset="UTF-8" />
<body>
<form action="#" th:action="@{/}" th:object="${personForm}" method="post">
<table>
<tr>
<td>Name:</td>
<td><input type="text" th:field="*{name}" /></td>
<td th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name Error</td>
</tr>
<tr>
<td>Age:</td>
<td><input type="text" th:field="*{age}" /></td>
<td th:if="${#fields.hasErrors('age')}" th:errors="*{age}">Age Error</td>
</tr>
<tr>
<td><button type="submit">Submit</button></td>
</tr>
</table>
</form>
</body>
</html>