@Valid 注解
用于验证对象中参数是否符合要求,不符合要求时返回message 的错误提示信息封装到(BindingResult errors)对象中
@PutMapping("/user/update")
public User updateUser(@Valid @RequestBody User user,BindingResult errors){
if(errors.hasErrors()){
errors.getAllErrors().stream().forEach(error ->{
System.out.println(error.getDefaultMessage());
});
}
user.setId(1);
return user;
}
然后在 User 类中添加验证信息的要求:
public class User {
@NotBlank(message = "用户名不能为空")
private String password;
}
@NotBlank注解在User实体类中password字段上,在updateUser方法中User user 对象前使用@Valid注解,表示调用方法时传入的参数password如果为空的话,会将错误信息封装到方法中BindingResult errors对象、
其他验证信息:
校验注解 | 说明 |
---|---|
@Null | 限制只能为null |
@NotNull | 限制必须不为null |
@AssertFalse | 限制必须为false |
@AssertTrue | 限制必须为true |
@DecimalMax(value) | 限制必须为一个不大于指定值的数字 |
@DecimalMin(value) | 限制必须为一个不小于指定值的数字 |
@Digits(integer,fraction) | 限制必须为一个小数,且整数部分的位数不能超过integer,小数部分的位数不能超过fraction |
@Future | 限制必须是一个将来的日期 |
@Max(value) | 限制必须为一个不大于指定值的数字 |
@Min(value) | 限制必须为一个不小于指定值的数字 |
@Past | 限制必须是一个过去的日期 |
@Pattern(value) | 限制必须符合指定的正则表达式 |
@Size(max,min) | 限制字符长度必须在min到max之间 |
@Past | 验证注解的元素值(日期类型)比当前时间早 |
@NotEmpty | 验证注解的元素值不为null且不为空(字符串长度不为0、集合大小不为0) |
@NotBlank | 验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@NotEmpty,@NotBlank只应用于字符串且在比较时会去除字符串的空格 |
验证注解的元素值是Email,也可以通过正则表达式和flag指定自定义的email格式 |
除表格展示之外还可以自定义验证信息:
public class User {
@MyConstraint(message = "这是一个测试")
private String username;
}
自定义的注解@MyConstraint:
@Constraint(validatedBy = {MyConstraintValidator.class})
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyConstraint {
String message();
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
下面是校验器:
// 泛型 第一个参数:注解类;第二个参数:校验对什么类型的数据生效
public class MyConstraintValidator implements ConstraintValidator<MyConstraint, Object> {
@Autowired
private UserService userService; // 注入userService说明 MyConstraintValidator实现ConstraintValidator 了接口,会自动生成对象注入到spring IOC容器中
@Override
public void initialize(MyConstraint constarintAnnotation) {
System.out.println("自定义验证注解 init");
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
System.out.println("valid");
// 。。。具体逻辑省略
return false; // 如果返回true,则验证通过;返回false,则返回message中信息
}
}
跟@Valid注解自带注解使用方式一样,只需要将自定义注解@MyConstraint添加到实体类属性即可生效