Spring Boot MVC表单验证示例
在本Spring Boot MVC教程中,我们将介绍如何使用标准验证注释来验证表单字段。
表单验证是Web应用程序中很重要的一部分,需要用户输入才能避免用户输入无效的值。我们还将看到如何在字段前面显示具有无效值的错误消息,以便用户可以重新输入以使其有效。
Starter依赖
我们将为此Spring Boot表单验证示例选择的Starter依赖项是
spring-boot-starter-web
spring-boot-starter-thymeleaf
spring-boot-devtools
本示例使用Thymeleaf模板进行查看,因此可查看百里香酸启动子。
每当classpath上的文件发生更改时,使用spring-boot-devtools的应用程序都会自动重启,因此我们不必每次都自行重建和重启服务器。
Maven – pom.xml
具有上述入门依赖项的pom.xml。
<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> <!-- For hot swapping --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency>
Bean验证API和Hibernate验证程序
对于表单字段验证,使用了Bean Validation API,该API定义了驻留在javax.validation.constraints包中的一些注释。
注意,Bean Validation API仅提供接口,Hibernate Validator是该API的实现。
仅通过包含spring-boot-starter-web,我们将获得所需的jar。我们需要做的就是在字段中使用注释来指定约束。
Java Bean验证API中定义的一些注释如下:
- @ NotBlank-带注释的元素不能为null,并且必须至少包含一个非空白字符。
- @NotEmpty-带注释的元素不能为null或者为空。
- @NotNull-带注释的元素不能为null。
- @ Size-带注释的元素大小必须在指定的边界之间。可以使用main和max属性指定边界。
- @ Digits-带注释的元素必须是可接受范围内的数字。
- @ Max-带注释的元素必须是一个数字,其值必须小于或者等于指定的最大值。
- @ Min-带注释的元素必须是一个数字,其值必须大于或者等于指定的最小值。
- @ Email-字符串必须是格式正确的电子邮件地址。
Spring Boot表单验证示例步骤
我们在这里构建的是Thymeleaf视图,这是用于用户注册的表单。所需的类是
1.一个Model bean类(User.java),其字段带有必需的约束。
2. userform.html Thymeleaf模板,它是用户注册表单UI。
3.在注册表单中单击"提交"按钮时,将进行字段验证,如果再次显示任何错误注册表单并显示错误消息。如果没有错误,则使用user.html Thymeleaf模板显示输入的用户数据。
带有验证错误的表单的屏幕截图
Spring Boot表单验证–模型类
有一个模型类User,其中包含字段和约束。
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
public class User {
@NotEmpty(message = "Field can't be left empty")
@Size(min=2, max=20, message = "Has to be in 2-20 chars range")
private String firstName;
@NotEmpty
@Size(min=2, max=20)
private String lastName;
@NotEmpty
@Email
private String email;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
如我们所见,字段带有必需的约束。
- firstName不能为null或者为空,并且必须包含2至20个字符。
- lastName不能为null或者为空,并且必须包含2至20个字符。
- 电子邮件不能为空,并且应该是格式正确的电子邮件。
如果未指定任何消息,则显示默认消息,我们可以使用"消息"属性指定自己的消息。
Spring Boot表单验证– Thymeleaf模板
在src / main / resources / templates中创建一个userform.html文件。
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Spring Boot form validation</title>
<link rel="stylesheet" th:href="@{/css/style.css}"/>
</head>
<body>
<h1>User Registration Form</h1>
<form action="#" th:action="@{/showUser}" th:object="${user}" method="post">
<table>
<tr>
<td>First Name:</td>
<td><input type="text" th:field="*{firstName}" placeholder="Enter First Name"/></td>
<td th:if="${#fields.hasErrors('firstName')}" th:errors="*{firstName}" class="error"></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" th:field="*{lastName}" placeholder="Enter Last Name"/></td>
<td th:if="${#fields.hasErrors('lastName')}" th:errors="*{lastName}" class="error"></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="text" th:field="*{email}" placeholder="email"/></td>
<td th:if="${#fields.hasErrors('email')}" th:errors="*{email}" class="error"></td>
</tr>
<tr>
<td><button type="submit">Submit</button></td>
</tr>
</table>
</form>
</body>
</html>
在表单标记中,将动作指定为" / showUser"(th:action =" @ {/ showUser}"),并且方法为post。此表单绑定的对象是用户对象(th:object =" $ {user}")
对于每个字段,都会添加一个新列以呈现验证错误消息。
<td th:if="${#fields.hasErrors('firstName')}" th:errors="*{firstName}" class="error"></td>
另一个用于显示用户数据的模板src / main / resources / templates / user.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>User Details</h1>
<table>
<tr><td th:text="'First Name: ' + ${user.firstName}"></td> </tr>
<tr><td th:text="'Last Name: ' + ${user.lastName}"></td> </tr>
<tr><td th:text="'Email: ' + ${user.email}"></td> </tr>
</table>
</body>
</html>
还有一个CSS类用于设置错误消息的样式,我们可能已经在src / main / resources / templates / userform.html文件中注意到了它的用法。
<link rel="stylesheet" th:href="@{/css/style.css}"/>
And here
<td th:if="${#fields.hasErrors('email')}" th:errors="*{email}" class="error">
因此,创建一个文件src / main / resources / static / css / style.css
.error {
color: red;
font-style: italic;
}
Spring Boot表单验证–控制器类
在UserController.java类中,有映射到URL路径的处理程序方法。
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import com.theitroad.sb.model.User;
@Controller
public class UserController {
@GetMapping(value = "/registerUser")
public String registerUser(Model model) {
model.addAttribute("user", new User());
return "userform";
}
@PostMapping(value="/showUser")
public String showUser(@Valid @ModelAttribute("user") User user, BindingResult result, Model model) {
if(result.hasErrors()) {
return "userform";
}
model.addAttribute("user", user);
return "user";
}
}
在showUser方法中,与User类对象一起使用了@Valid注释。使用@Valid注释可确保对在对象及其属性上定义的约束进行验证。
使用BindingResult实例检查是否存在验证错误。如果存在验证错误,将再次显示带有错误消息的注册表格,否则返回逻辑视图名称" user",该名称将呈现user.html模板。
应用类别
我们可以通过执行具有main方法的应用程序类来运行该应用程序。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootProjectApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootProjectApplication.class, args);
}
}
成功启动应用程序后,我们可以根据控制器映射使用URL访问应用程序。
http:// localhost:8080 / registerUser
http:// localhost:8080 / showUser

