springboot中参数校验
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
使用:
public class LoginVo { @NotNull @IsMobile private String mobile; @NotNull @Length(min=32) private String password; public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "LoginVo [mobile=" + mobile + ", password=" + password + "]"; } }
使用注解就可以了
那么怎么自定i注解呢:
package com.cxy.validator; import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.CONSTRUCTOR; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER }) @Retention(RUNTIME) @Documented @Constraint(validatedBy = {IsMobileValidator.class }) public @interface IsMobile { boolean required() default true; String message() default "手机号码格式错误"; Class<?>[] groups() default { }; Class<? extends Payload>[] payload() default { }; }
@Constraint(validatedBy = {IsMobileValidator.class })可以看到这句话:
进行一个处理
package com.cxy.validator; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import com.cxy.util.ValidatorUtil; import org.apache.commons.lang3.StringUtils; public class IsMobileValidator implements ConstraintValidator<IsMobile, String> { private boolean required = false; public void initialize(IsMobile constraintAnnotation) { required = constraintAnnotation.required(); } 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); } } } }
其中使用到一个util
public class ValidatorUtil { private static final Pattern mobile_pattern = Pattern.compile("1\\d{10}"); public static boolean isMobile(String src) { if(StringUtils.isEmpty(src)) { return false; } Matcher m = mobile_pattern.matcher(src); return m.matches(); } // public static void main(String[] args) { // System.out.println(isMobile("18912341234")); // System.out.println(isMobile("1891234123")); // } }
笔记转移,由于在有道云的笔记转移,写的时间可能有点久,如果有错误的地方,请指正