概述
SpringMVC可以不需要再代码中使用if进行表单值的判断,直接使用validation在pojo上标注实现校验
pom依赖
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.10.Final</version>
</dependency>
在pojo上进行标注
- 一些常用的注解
@NotNull 和 @NotEmpty 和@NotBlank 区别
@NotEmpty 用在集合类上面
@NotBlank 用在String上面
@NotNull 用在基本类型上
- 示例代码
public class User {
@NotNull
private String name;
@NotNull
private String password;
@NotNull
@Max(50)
@Min(18)
private Integer age;
@NotNull
private String sex;
set,get...........
}
在controller中使用
- 使用@Valid标注要实现校验的对象,后面紧跟Errors参数
- 当表单校验出现错误时errors.hasErrors()为true
@RequestMapping("/doForm")
public String doForm(@Valid User user, Errors errors){
if (errors.hasErrors()){
System.out.println("有错误了"+errors.getErrorCount());
}
System.out.println(user);
return "redirect:form";
}