org.springframework.boot spring-boot-starter-validation
提供了很多注解来辅助校验
在实体类字段上使用(请求过程中会自动校验)@Data public class LoginVo { @NotNull private String mobile; @NotNull//不为null @Length(min = 32)//长度最小为32 private String password; }
注解内容:
@Data public class LoginVo { @NotNull @IsMobile private String mobile; @NotNull @Length(min = 32) private String password; }通过validate中的注解直接复制创建注解:
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE }) @Retention(RUNTIME) @documented @Constraint(validatedBy = {IsMobilevalidator.class})//IsMobilevalidator注解校验的类 public @interface IsMobile { boolean required() default true;//判断是否必填 String message() default "手机号码格式错误"; Class>[] groups() default { }; Class extends Payload>[] payload() default { }; }自定义校验规则
public class IsMobilevalidator implements ConstraintValidator{ private boolean required = false; @Override public void initialize(IsMobile constraintAnnotation) { required = constraintAnnotation.required(); } @Override public boolean isValid(String value, ConstraintValidatorContext context) { if (required){ return ValidatorUtil.isMobile(value); }else { if (StringUtils.isEmpty(value)){ return true; }else { return ValidatorUtil.isMobile(value); } } } }
public class ValidatorUtil { //使用正则表达式校验手机号码 private static final Pattern mobile_pattern = Pattern.compile("[1]([3-9])[0-9]{9}$"); public static boolean isMobile(String mobile){ if (StringUtils.isEmpty(mobile)) { return false; } Matcher matcher = mobile_pattern.matcher(mobile); return matcher.matches(); } }测试
@RequestMapping("/doLogin") @ResponseBody public RespBean doLogin(@Valid LoginVo loginVo){//@Valid启动注解校验 log.info(loginVo.toString());//使用@Slf4j注解打印日志 return userService.login(loginVo); }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)