Spring Boot 2 + Thymeleaf:服务器端表单验证

时间:2023-03-09 21:40:51
Spring Boot 2 + Thymeleaf:服务器端表单验证

表单验证分为前端验证和服务器端验证。
服务器端验证方面,Java提供了主要用于数据验证的JSR 303规范,而Hibernate Validator实现了JSR 303规范。
项目依赖加入spring-boot-starter-thymeleaf时,默认就会加入Hibernate Validator的依赖。

开发环境:IntelliJ IDEA 2019.2.2
Spring Boot版本:2.1.8

新建一个名称为demo的Spring Boot项目。

1、pom.xml

       <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>

2、src/main/java/com/example/demo/User.java

package com.example.demo;

import org.hibernate.validator.constraints.Length;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size; public class User {
@NotBlank(message = "用户名不能为空")
String name;
@Length(min = 11, max = 11, message = "手机号长度必须11位")
String phone;
@Size(min = 6, max = 20, message = "密码长度6-20位")
String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

3、src/main/java/com/example/demo/FormController.java

package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping; import javax.validation.Valid;
import java.util.List; @Controller
public class FormController {
@RequestMapping("/{form}")
public String form(@PathVariable String form, @ModelAttribute User user){
return form;
} @PostMapping("/submit")
public String submit(@Valid User user, BindingResult result){
if (result.hasErrors()) {
List<ObjectError> list = result.getAllErrors();
for (ObjectError error : list) {
System.out.println(error.getDefaultMessage());
}
return "form";
}
//业务逻辑处理
return "form";
} }

4、src/main/resources/templates/form.html

前端通过#fields对象输出错误信息有2种方式,1种是在每个字段后面输出,另1种是全部在一起输出。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>表单的提交处理</title>
<style>
.fieldError{color: red}
</style>
</head>
<body>
<form method="post" th:action="@{/submit}" th:object="${user}">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" th:field="*{name}" />
<span class="fieldError" th:if="${#fields.hasErrors('*{name}')}" th:errors="*{name}"></span>
</td>
</tr>
<tr>
<td>手机号:</td>
<td><input type="text" th:field="*{phone}" />
<span class="fieldError" th:if="${#fields.hasErrors('*{phone}')}" th:errors="*{phone}"></span>
</td>
</tr>
<tr>
<td>密码:</td>
<td><input type="text" th:field="*{password}" />
<span class="fieldError" th:if="${#fields.hasErrors('*{password}')}" th:errors="*{password}"></span>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="提交" />
<div th:each="err : ${#fields.errors('*')}">
<span th:text="${err}" class="fieldError"></span>
</div>
</td>
</tr>
</table>
</form>
</body>
</html>

启动服务后,浏览器访问http://localhost:8080/form,点击提交按钮,结果如下:

Spring Boot 2 + Thymeleaf:服务器端表单验证