Hibernate validator使用以及自定义校验器注解

2018-06-23  本文已影响0人  DFYang

Hibernate Validator常用注解 常用注解.png

1.创建自定义校验器
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MyConstraintValidator.class)
public @interface MyConstraint {
    /**
    * @Description: 错误提示
    */
    String message() default "请输入正确性別";

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };
}
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class MyConstraintValidator implements ConstraintValidator<MyConstraint, String> {  
//String为校验的类型
    @Override
    public void initialize(MyConstraint myConstraint) {
        //启动时执行
    }

    /**
    * @Description: 自定义校验逻辑
    */
    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if (!(s.equals("男") || s.equals("女")))
            return false;
        return true;
    }
}

@Target用于指定使用范围,该处限定只能在字段上使用
@Retention(RetentionPolicy.RUNTIME)表示注解在运行时可以通过反射获取到
@Constraint(validatedBy = xxx.class)指定该注解校验逻辑

2.创建校验实体,使用Hibernate Validator自带注解以及自定义的注解
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;

//@Data为lombok注解,用于省略get(),set()方法
@Data
public class User {
    @Length(min = 8, max = 18, message = "用户名长度必须为8-18")
    private String username;

    @Length(min = 8, max = 18, message = "密码长度必须为8-18")
    private String password;

    @MyConstraint
    private String sex;

    @Email
    private String email;
}
3.写一个controller
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
public class UserController {
   @PutMapping("/user")
    public String test(@Valid @RequestBody User user, BindingResult result){
       StringBuilder sb = new StringBuilder();
        if (result.hasErrors()){
            //记录错误信息
            result.getAllErrors().stream()
                    .forEach(error -> sb.append(error.getDefaultMessage() + "/"));
        }
        return sb.toString();
   }
}
4.此处使用postman发送请求,输入错误的密码,性别,email
result.png
5.错误信息如下
result.png
上一篇下一篇

猜你喜欢

热点阅读