Jelajahi Sumber

优化自定义参数校验逻辑

woody 11 bulan lalu
induk
melakukan
09cba96025

+ 16 - 9
framework-common/src/main/java/com/chelvc/framework/common/annotation/Regexes.java → framework-common/src/main/java/com/chelvc/framework/common/annotation/Numbers.java

@@ -9,33 +9,40 @@ import java.lang.annotation.Target;
 import javax.validation.Constraint;
 import javax.validation.Payload;
 
-import com.chelvc.framework.common.validator.RegexValidator;
+import com.chelvc.framework.common.validator.NumberValidator;
 
 /**
- * 参数正则表达式校验注解
+ * 数字参数校验注解
  *
  * @author Woody
- * @date 2024/4/27
+ * @date 2024/4/28
  */
 @Inherited
 @Documented
 @Retention(RetentionPolicy.RUNTIME)
-@Constraint(validatedBy = RegexValidator.class)
+@Constraint(validatedBy = NumberValidator.class)
 @Target({ElementType.FIELD, ElementType.PARAMETER})
-public @interface Regexes {
+public @interface Numbers {
     /**
-     * 获取正则表达式
+     * 获取最小值,当值>0时生效
      *
-     * @return 正则表达式
+     * @return 数字最小值
      */
-    String value();
+    double min() default -1;
+
+    /**
+     * 获取最大值,当值>0时生效
+     *
+     * @return 数字最大值
+     */
+    double max() default -1;
 
     /**
      * 获取异常消息
      *
      * @return 异常消息
      */
-    String message() default "Invalid format";
+    String message() default "Invalid number";
 
     /**
      * 获取对象分组(固定写法)

+ 68 - 0
framework-common/src/main/java/com/chelvc/framework/common/annotation/Strings.java

@@ -0,0 +1,68 @@
+package com.chelvc.framework.common.annotation;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Inherited;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import javax.validation.Constraint;
+import javax.validation.Payload;
+
+import com.chelvc.framework.common.util.StringUtils;
+import com.chelvc.framework.common.validator.StringValidator;
+
+/**
+ * 字符串参数校验注解
+ *
+ * @author Woody
+ * @date 2024/4/27
+ */
+@Inherited
+@Documented
+@Retention(RetentionPolicy.RUNTIME)
+@Constraint(validatedBy = StringValidator.class)
+@Target({ElementType.FIELD, ElementType.PARAMETER})
+public @interface Strings {
+    /**
+     * 获取最小长度,当值>0时生效
+     *
+     * @return 字符串长度
+     */
+    int min() default -1;
+
+    /**
+     * 获取最大长度,当值>0时生效
+     *
+     * @return 字符串长度
+     */
+    int max() default -1;
+
+    /**
+     * 获取正则表达式
+     *
+     * @return 正则表达式
+     */
+    String regex() default StringUtils.EMPTY;
+
+    /**
+     * 获取异常消息
+     *
+     * @return 异常消息
+     */
+    String message() default "Invalid string";
+
+    /**
+     * 获取对象分组(固定写法)
+     *
+     * @return 对象数组
+     */
+    Class<?>[] groups() default {};
+
+    /**
+     * 获取载体对象(固定写法)
+     *
+     * @return 载体对象数组
+     */
+    Class<? extends Payload>[] payload() default {};
+}

+ 40 - 11
framework-common/src/main/java/com/chelvc/framework/common/validator/DateValidator.java

@@ -2,6 +2,7 @@ package com.chelvc.framework.common.validator;
 
 import java.time.LocalDate;
 import java.time.LocalDateTime;
+import java.util.Collection;
 import java.util.Date;
 import javax.validation.ConstraintValidator;
 import javax.validation.ConstraintValidatorContext;
@@ -18,6 +19,40 @@ import com.chelvc.framework.common.util.DateUtils;
 public class DateValidator implements ConstraintValidator<Dates, Object> {
     private Dates annotation;
 
+    /**
+     * 日期对象转换
+     *
+     * @param value 参数值
+     * @return 日期对象实例
+     */
+    private Date convert(Object value) {
+        if (value instanceof Date) {
+            return (Date) value;
+        } else if (value instanceof LocalDate) {
+            return DateUtils.convert((LocalDate) value);
+        } else if (value instanceof LocalDateTime) {
+            return DateUtils.convert((LocalDateTime) value);
+        }
+        return null;
+    }
+
+    /**
+     * 校验日期参数
+     *
+     * @param value 参数值
+     * @return true/false
+     */
+    private boolean validate(Object value) {
+        Date date = this.convert(value);
+        if (date == null) {
+            return true;
+        }
+        int min = this.annotation.min(), max = this.annotation.max();
+        long datetime = date.getTime(), now = System.currentTimeMillis();
+        return (min == Integer.MIN_VALUE || datetime >= now + min * 1000)
+                && (max == Integer.MAX_VALUE || datetime <= now + max * 1000);
+    }
+
     @Override
     public void initialize(Dates annotation) {
         this.annotation = annotation;
@@ -25,18 +60,12 @@ public class DateValidator implements ConstraintValidator<Dates, Object> {
 
     @Override
     public boolean isValid(Object value, ConstraintValidatorContext context) {
-        if (this.annotation == null
-                || !(value instanceof Date || value instanceof LocalDate || value instanceof LocalDateTime)) {
-            return true;
-        }
-        int min = this.annotation.min(), max = this.annotation.max();
-        if (min == Integer.MIN_VALUE && max == Integer.MAX_VALUE) {
+        if (this.annotation == null || (this.annotation.min() == Integer.MIN_VALUE
+                && this.annotation.max() == Integer.MAX_VALUE)) {
             return true;
+        } else if (value instanceof Collection) {
+            return ((Collection<?>) value).stream().allMatch(this::validate);
         }
-        Date date = value instanceof Date ? (Date) value : value instanceof LocalDate ?
-                DateUtils.convert((LocalDate) value) : DateUtils.convert((LocalDateTime) value);
-        long datetime = date.getTime(), now = System.currentTimeMillis();
-        return (min == Integer.MIN_VALUE || datetime >= now + min * 1000)
-                && (max == Integer.MAX_VALUE || datetime <= now + max * 1000);
+        return this.validate(value);
     }
 }

+ 47 - 0
framework-common/src/main/java/com/chelvc/framework/common/validator/NumberValidator.java

@@ -0,0 +1,47 @@
+package com.chelvc.framework.common.validator;
+
+import java.util.Collection;
+import javax.validation.ConstraintValidator;
+import javax.validation.ConstraintValidatorContext;
+
+import com.chelvc.framework.common.annotation.Numbers;
+
+/**
+ * 数字参数验证器
+ *
+ * @author Woody
+ * @date 2024/4/27
+ */
+public class NumberValidator implements ConstraintValidator<Numbers, Object> {
+    private Numbers annotation;
+
+    /**
+     * 校验数字参数
+     *
+     * @param value 参数值
+     * @return true/false
+     */
+    private boolean validate(Object value) {
+        if (!(value instanceof Number)) {
+            return true;
+        }
+        double number = ((Number) value).doubleValue();
+        double min = this.annotation.min(), max = this.annotation.max();
+        return (min < 1 || number >= min) && (max < 1 || number <= max);
+    }
+
+    @Override
+    public void initialize(Numbers annotation) {
+        this.annotation = annotation;
+    }
+
+    @Override
+    public boolean isValid(Object value, ConstraintValidatorContext context) {
+        if (this.annotation == null || (this.annotation.min() < 1 && this.annotation.max() < 1)) {
+            return true;
+        } else if (value instanceof Collection) {
+            return ((Collection<?>) value).stream().allMatch(this::validate);
+        }
+        return this.validate(value);
+    }
+}

+ 20 - 4
framework-common/src/main/java/com/chelvc/framework/common/validator/PagingValidator.java

@@ -1,5 +1,6 @@
 package com.chelvc.framework.common.validator;
 
+import java.util.Collection;
 import javax.validation.ConstraintValidator;
 import javax.validation.ConstraintValidatorContext;
 
@@ -15,6 +16,21 @@ import com.chelvc.framework.common.model.Paging;
 public class PagingValidator implements ConstraintValidator<Pages, Object> {
     private Pages annotation;
 
+    /**
+     * 校验分页参数
+     *
+     * @param value 参数值
+     * @return true/false
+     */
+    private boolean validate(Object value) {
+        if (!(value instanceof Paging)) {
+            return true;
+        }
+        Paging paging = (Paging) value;
+        int size = this.annotation.size(), total = this.annotation.total();
+        return (size < 1 || paging.getSize() <= size) && (total < 1 || paging.getNumber() * paging.getSize() <= total);
+    }
+
     @Override
     public void initialize(Pages annotation) {
         this.annotation = annotation;
@@ -22,11 +38,11 @@ public class PagingValidator implements ConstraintValidator<Pages, Object> {
 
     @Override
     public boolean isValid(Object value, ConstraintValidatorContext context) {
-        if (this.annotation == null || !(value instanceof Paging)) {
+        if (this.annotation == null || (this.annotation.size() < 1 && this.annotation.total() < 1)) {
             return true;
+        } else if (value instanceof Collection) {
+            return ((Collection<?>) value).stream().allMatch(this::validate);
         }
-        Paging paging = (Paging) value;
-        int size = this.annotation.size(), total = this.annotation.total();
-        return (size < 1 || paging.getSize() <= size) && (total < 1 || paging.getNumber() * paging.getSize() <= total);
+        return this.validate(value);
     }
 }

+ 0 - 31
framework-common/src/main/java/com/chelvc/framework/common/validator/RegexValidator.java

@@ -1,31 +0,0 @@
-package com.chelvc.framework.common.validator;
-
-import javax.validation.ConstraintValidator;
-import javax.validation.ConstraintValidatorContext;
-
-import com.chelvc.framework.common.annotation.Regexes;
-import com.chelvc.framework.common.util.StringUtils;
-
-/**
- * 参数正则表达验证器
- *
- * @author Woody
- * @date 2024/4/27
- */
-public class RegexValidator implements ConstraintValidator<Regexes, Object> {
-    private Regexes annotation;
-
-    @Override
-    public void initialize(Regexes annotation) {
-        this.annotation = annotation;
-    }
-
-    @Override
-    public boolean isValid(Object value, ConstraintValidatorContext context) {
-        if (this.annotation == null || !(value instanceof CharSequence)) {
-            return true;
-        }
-        String regex = this.annotation.value();
-        return StringUtils.isEmpty(regex) || StringUtils.matches((CharSequence) value, regex);
-    }
-}

+ 51 - 0
framework-common/src/main/java/com/chelvc/framework/common/validator/StringValidator.java

@@ -0,0 +1,51 @@
+package com.chelvc.framework.common.validator;
+
+import java.util.Collection;
+import javax.validation.ConstraintValidator;
+import javax.validation.ConstraintValidatorContext;
+
+import com.chelvc.framework.common.annotation.Strings;
+import com.chelvc.framework.common.util.StringUtils;
+
+/**
+ * 字符串参数验证器
+ *
+ * @author Woody
+ * @date 2024/4/27
+ */
+public class StringValidator implements ConstraintValidator<Strings, Object> {
+    private Strings annotation;
+
+    /**
+     * 校验字符串参数
+     *
+     * @param value 参数值
+     * @return true/false
+     */
+    private boolean validate(Object value) {
+        if (!(value instanceof CharSequence)) {
+            return true;
+        }
+        CharSequence source = (CharSequence) value;
+        String regex = this.annotation.regex();
+        int min = this.annotation.min(), max = this.annotation.max();
+        return (StringUtils.isEmpty(regex) || StringUtils.matches(source, regex))
+                && (min < 1 || source.length() >= min) && (max < 1 || source.length() <= max);
+    }
+
+    @Override
+    public void initialize(Strings annotation) {
+        this.annotation = annotation;
+    }
+
+    @Override
+    public boolean isValid(Object value, ConstraintValidatorContext context) {
+        if (this.annotation == null || (StringUtils.isEmpty(this.annotation.regex())
+                && this.annotation.min() < 1 && this.annotation.max() < 1)) {
+            return true;
+        } else if (value instanceof Collection) {
+            return ((Collection<?>) value).stream().allMatch(this::validate);
+        }
+        return this.validate(value);
+    }
+}