单个类验证
通过JSR-303
验证框架加Hibernate Validator
机制进行验证
先引入依赖:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.1.0.Final</version>
</dependency>
然后在📃springmvc-servlet.xml
中添加相关配置
<bean class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" id="validatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>
</bean>
<mvc:annotation-driven validator="validatorFactoryBean"/>
定义实体类Student
,加入验证注解
@Data
public class Student {
@NotNull(message = "姓名不能为空")
String name;
@NotNull @Min(18) @Max(30)
Integer age;
@Email(message = "邮箱格式错误")
String email;
}
jsp中:
<form action="/validate" method="post">
<table>
<tr>
<td>学生姓名:</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>学生邮箱:</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td>学生年龄:</td>
<td><input type="text" name="age"></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="提交">
</td>
</tr>
</table>
</form>
Controller中,输出错误对象与信息
@Controller
public class MyController {
@GetMapping("/user")
public Object sayHello(){
return "hello";
}
@RequestMapping("/validate")
@ResponseBody
public Map<String,Object> validate(
@Validated Student student, BindingResult errors)
{
List<ObjectError> oes = errors.getAllErrors();
for (ObjectError oe : oes) {
String key, msg;
if (oe instanceof FieldError) {
FieldError fe = (FieldError) oe;
//获取错误验证字段名
//如name,age,email
key = fe.getField();
} else {
//对象名,person
key = oe.getObjectName();
}
msg = oe.getDefaultMessage();
System.out.println(key+":"+msg);
}
return null;
}
}
输出:
email:邮箱格式错误
age:最大不能超过30
分组校验
首先定义两个空接口validGroup1
、validGroup2
,在校验注解上添加
@Data
public class Student {
@NotNull(message = "姓名不能为空",groups = validGroup1.class)
String name;
@NotNull @Min(18) @Max(30)
Integer age;
@Email(message = "邮箱格式错误",groups = validGroup2.class)
String email;
}
然后验证时加上要验证的组即可:
@Controller
public class MyController {
@RequestMapping("/validate")
@ResponseBody
public Map<String,Object> validate(
@Validated(validGroup1.class) Person person, BindingResult errors)
{}
常见的校验注解
@Null、@NotNull
:必须为空/不为空@AssertTrue、@AssertFalse
:必须为True/FalseMin(value)、Max(value)
:为数字,其最大/最小值DecimalMin(value)、DecimalMax(value)
:同上,但是接受BigDecimal
Size(max=, min=)
:元素大小在范围内@Past、@Future:
:注解的日期必须是过去/将来的@Email
:必须为邮箱格式@Pattern(regex=,flag=)
:必须符合指定的正则表达式@NotEmpty
:字符串非空@Length(min= ,max= )
:字符串长度范围