SpringBoot 表单后台验证
表单验证分为前端验证和服务器端验证。
服务器端验证方面,Java提供了主要用于数据验证的JSR 303规范,而Hibernate Validator实现了JSR 303规范。
旧版本的SpringBoot项目依赖加入spring-boot-starter-thymeleaf
时,默认就会加入Hibernate Validator
的依赖。
新版本的SpringBoot需要我们自己加入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
一、新建一个DTO对象,进行页面验证
UserDTO.java
@Data
public class UserDTO {
private Integer userPkid;
@NotBlank(message = "用户名不能为空")
private String username;
@NotBlank(message = "密码不能为空")
@Pattern(regexp = "^.{6,20}$",message = "密码必须在6-20位之间")
private String password;
@Pattern(regexp = "^[\u4e00-\u9fa5]{2,10}$",message = "用户昵称必须是中文在2-10个字符之间")
private String nickname;
private LocalDateTime regTime;
private List<Role> roles;
}
这里只用了几个注解,下面列下清单,平时可以参考用;
二、创建Controller
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/{register}")
public String form(@PathVariable String register, @ModelAttribute("user") UserDTO user){
return register;
}
@PostMapping("reg")
public String validate(@Valid @ModelAttribute("user") UserDTO user, BindingResult result){
System.out.println("userDTO = " + user);
if (result.hasErrors()) {
List<ObjectError> list = result.getAllErrors();
for (ObjectError error : list) {
System.out.println(error.getDefaultMessage());
}
return "register";
}
System.out.println("userDTO = " + user);
return "register";
}
}
三、页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.fieldError{
color:red;
}
</style>
</head>
<body>
<form th:action="@{/user/reg}" method="post" th:object="${user}">
用户名: <input type="text" name="username" th:field="*{username}">
<span class="fieldError" th:if="${#fields.hasErrors('*{username}')}" th:errors="*{username}"></span>
<br>
密 码: <input type="password" name="password"> <span class="fieldError" th:errors="*{password}"></span>
<input type="submit" value="添加">
</form>
</body>
</html>
Comments