自定义注解实现对用户名的存在验证
- 创建UserNameExistAnnotation
@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD,ElementType.FIELD}) @Constraint(validatedBy = UserNameExistValidator.class) public @interface UserNameExistAnnotation { String message() default "出错了!!!"; Class<?>[] groups() default {}; Class<?extends Payload>[] payload() default {}; }
- 创建UserNameExistValidator类
public class UserNameExistValidator implements ConstraintValidator<UserNameExistAnnotation,String> { @Autowired private UserMapper userMapper; public void initialize(UserNameExistAnnotation constraintAnnotation){ System.out.println("UserNameExistValidator 初始化了"); } public boolean isValid(String value, ConstraintValidatorContext contrxt){ //查询是否存在该用户名 User user=userMapper.queryUserByUsername(value); if(user!=null){ System.out.println(ReflectionToStringBuilder.toString(user, ToStringStyle.MULTI_LINE_STYLE)); return false; } return true; } }
- 在UserVo的username字段上添加
@UserNameExistAnnotation(message="该用户名已存在")
注解public class UserVo { private Integer id; @Length(min=2,max=18,message="请输入2-18位之间的用户名") @UserNameExistAnnotation(message="该用户名已存在") private String username; @Pattern(regexp = "[1-9]([0-9]{2,10})",message = "请输入6-16位之间的任意数字字母或者-_") private String password; @Min(value = 12,message = "年龄必须满足18岁以上") private Integer age; @Past(message = "生日必须是过去的日期") private Date birthday; @NotNull private String email; ... }
- 启动验证
- 在传入对象的前面添加@Valid注解,添加BindingResult收集错误信息,取消spring对错误URL的自动拦截
@PostMapping public JsonResult insertUser(@Valid @RequestBody UserVo vo,BindingResult bindingResult){ bindingResult.getAllErrors().forEach(objectError -> { FieldError fieldError=(FieldError)objectError; System.out.println(fieldError.getField()+" : "+fieldError.getDefaultMessage()); }); System.out.println(vo); return JsonResult.isOk(vo); }