package org.linlinjava.litemall.core.validator; import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.RUNTIME; @Target({METHOD, FIELD, PARAMETER}) @Retention(RUNTIME) @Documented @Constraint(validatedBy = OrderValidator.class) public @interface Order { String message() default "排序类型不支持"; String[] accepts() default {"desc", "asc"}; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
package org.linlinjava.litemall.core.validator; import com.google.common.collect.Lists; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.util.List; public class OrderValidator implements ConstraintValidator<Order, String> { private List<String> valueList; @Override public void initialize(Order order) { valueList = Lists.newArrayList(); for (String val : order.accepts()) { valueList.add(val.toUpperCase()); } } @Override public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) { if (!valueList.contains(s.toUpperCase())) { return false; } return true; } }
package org.linlinjava.litemall.core.validator; import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.RUNTIME; @Target({METHOD, FIELD, PARAMETER}) @Retention(RUNTIME) @Documented @Constraint(validatedBy = SortValidator.class) public @interface Sort { String message() default "排序字段不支持"; String[] accepts() default {"add_time", "id"}; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
package org.linlinjava.litemall.core.validator; import com.google.common.collect.Lists; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.util.List; public class SortValidator implements ConstraintValidator<Sort, String> { private List<String> valueList; @Override public void initialize(Sort sort) { valueList = Lists.newArrayList(); for (String val : sort.accepts()) { valueList.add(val.toUpperCase()); } } @Override public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) { if (!valueList.contains(s.toUpperCase())) { return false; } return true; } }