基于javax手写SpringMvc验证器

@SalaryValidate

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Constraint(validatedBy = SalaryValidator.class) //具体的实现
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Documented
public @interface SalaryValidate {
	//提示信息,可以写死,可以填写国际化的key
	String message() default "{javax.validation.constraints.SalaryValidate}";
	String regexp() default "";

	//下面这两个属性必须添加
	Class<?>[] groups() default {};

	Class<? extends Payload>[] payload() default {};

}

SalaryValidator

import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.math.BigDecimal;
import java.util.regex.Pattern;

public class SalaryValidator implements ConstraintValidator<SalaryValidate, BigDecimal> {
    private String regexp;

    public SalaryValidator(String s) {
        throw new IllegalArgumentException("请输入正确金额");
    }

    /**
     * 初始参数,获取注解中的值
     */
    @Override
    public void initialize(SalaryValidate salaryValidate) {
        this.regexp=salaryValidate.regexp();
    }

    @Override
    public boolean isValid(BigDecimal value, ConstraintValidatorContext context) {
        if (StringUtils.isBlank(regexp)) {
            throw new IllegalArgumentException("表达式不能为空");
        }
        if (value == null) {
            return true;
        }
        if (Pattern.matches(regexp, value.toString())) {
            return true;
        } else {
            throw new IllegalArgumentException("请输入正确金额");
        }
    }
}

实体类

class Empoyee{
@SalaryValidate(regexp="",message="")
private BigDecimal salary;
}

控制层

@PutMapping
updateEmpoyee(@ApiParam("薪水") @RequestParam @Valid Empoyee e)

javax.validation.constraints 原生验证器

你可能感兴趣的:(SpringMvc)