1.在pom.xml添加依赖
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.1.7.Final</version>
</dependency>
2.在实体类中添加判断条件
@Data
public class Book {
private int id;
@NotBlank
private String name;
private String author;
@Min(0)
private int tid;
@Min(0)
private double price;
private String descri;
private String photo;
@DateTimeFormat(pattern = "yyyy-mm-dd")
private Date pubdate;
private Type type;
}
3.controller增加
public String tooAdd(@Validated Book book, BindingResult result, HttpServletRequest request,Model model, MultipartFile photox) throws IOException {
model.addAttribute("book",book);
if (result.hasErrors()){
// List<ObjectError> errorList = result.getAllErrors();
// for(ObjectError error : errorList){
// System.out.println(error.getDefaultMessage());
// }
System.out.println(result.hasErrors());
List<Type> types=bookServer.selectTypeAll();
model.addAttribute("types",types);
return "book/add1";
}
...............}
4.view层修改
1.th:classappend="${#fields.hasErrors('name')}? 'is-invalid'"
2.<div class="invalid-feedback"> <ul style="margin: 0px;"> <li th:each="err:${#fields.errors('name')}" th:text="${err}"></li> </ul> </div>
<div class="col-sm-10">
<input type="text" class="form-control" th:classappend="${#fields.hasErrors('name')}? 'is-invalid'" id="inputName" name="name" th:field="*{name}">
<div class="invalid-feedback">
<ul style="margin: 0px;">
<li th:each="err:${#fields.errors('name')}" th:text="${err}"></li>
</ul>
</div>
</div>