spring-boot-starter-validation基本用法
1.引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
或者
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2.直接在pojo类属性中添加约束
public class Book implements Serializable {
@NotEmpty(message = "密码不能为空")
@Length(min=6,max=8,message = "密码长度为6-8")
@Pattern(regexp = "[a-zA-z]*",message = "密码不合法")
private String password;
}
3.Controller中,直接添加@Validated进行验证,与BindingResult类配合获取验证结果。
@RequestMapping(value = "/create", method = RequestMethod.POST)
public String postBook(ModelMap map,
@ModelAttribute @Validated Book book,
BindingResult bindingResult) {
if(bindingResult.hasErrors()){
map.addAttribute("action","create");
return BOOK_FORM;
}
bookService.insertByBook(book);
return REDIRECT_TO_BOOK_HOME;
}
4.thymeleaf前端获取结果:#fields.hasErrors(所需字段)
<div class="form-group">
<label for="book_password" class="col-sm-2 control-label">密码:</label>
<div class="col-xs-4">
<input type="text" class="form-control" id="book_password"
name="name" th:value="${book.password}" th:field="*{book.password}"/>
</div>
<label class="col-sm-2 control-label text-danger"
th:if="${#fields.hasErrors('book.password')}"
th:errors="*{book.password}">
姓名有误!</label>
</div>