springboot中参数校验
Posted 丁春秋
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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")); // } }
以上是关于springboot中参数校验的主要内容,如果未能解决你的问题,请参考以下文章
SpringBoot - 使用Assert校验让业务代码更简洁
SpringBoot - 使用Assert校验让业务代码更简洁
springboot使用hibernate validator校验