springmvc_参数校验自定义注解

调用的例子

@PostMapping("/create")
public void create(@RequestBody @Valid ProductSerCreateInput productSerCreateInput, Errors errors) {
   ApiException.maybeThrowValidationError(errors);
}

其中ApiException为

package com.cmiinv.shp.util.api;

import lombok.Getter;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;

import java.util.stream.Collectors;

/**
 * @author LiuQi
 */
public class ApiException extends RuntimeException implements MessageSourceResolvable {

	@Getter
	private String[] codes;

	@Getter
	private Object[] arguments;

	@Override
	public String getDefaultMessage() {
		if (getMessage() != null) {
			return getMessage();
		} else if (getCause() != null) {
			return getCause().getMessage();
		} else {
			return null;
		}
	}

	public ApiException(String code, Object... arguments) {
		this(code, arguments, null, null);
	}

	public ApiException(String code, Object[] arguments, String message) {
		this(code, arguments, message, null);
	}

	public ApiException(String code, Object[] arguments, Throwable cause) {
		this(code, arguments, null, cause);
	}

	public ApiException(String code, Object[] arguments, String message, Throwable cause) {
		super(message, cause);
		this.codes = new String[]{code};
		this.arguments = arguments;
	}

	public String getCode() {
		return codes[0];
	}

	public static void maybeThrowValidationError(Errors errors) {
		if (errors != null && errors.hasErrors()) {
			String message = errors.getAllErrors().stream()
					.filter(objectError -> objectError instanceof FieldError)
					.map(objectError -> {
						FieldError fieldError = (FieldError) objectError;
						return "{" + fieldError.getField() + "}" + fieldError.getDefaultMessage();
					})
					.collect(Collectors.joining(";"));
			throw new ApiException(ErrorCodes.INVALID_INPUT, null, message);
		}
	}

	public static ApiException propagate(String errorCode, Object... arguments) {
		return new ApiException(errorCode, arguments);
	}

}

javax.validation.Valid

@Valid启用实体类中的自定义注解,BindingResult 用来返回错误信息

//import org.springframework.validation.BindingResult;
//import org.springframework.validation.Errors;
public Xxxx login(@Valid xxxModel , BindingResult bindingResult){
    if(bindingResult.hasErrors()){//返回具体的错误信息
      System.out.println("message="+bindingResult.getFieldError().getDefaultMessage());  //返回的具体信息
    }
}
public Xxxx login(@Valid xxxModel , Errors errors){
if(errors != null && errors.hasErrors()){
  String message = errors.getAllErrors().stream()
    .filter(objectError -> objectError instanceof FieldError)
    .map(objectError -> {
        FieldError fieldError = (FieldError) objectError;
        return "{" + fieldError.getField() + "}" + fieldError.getDefaultMessage();
        })
    .collect(Collectors.joining(";"));
  System.out.println("message="+message);
}
}
常用的自定义注解
@NotEmpty(message = "password 为空")   //javax.validation.constraints.NotEmpty;
@Min //不能低于某个值
@AssertFalse //该字段为false时才能验证通过
@AssertTrue  //该字段为true时才能验证通过
@DecimalMax  //验证小数的最大值@DecimalMax(value = "12.35")
@DecimalMin  //验证小数的最小值
@Digits(integer = 2, fraction = 2) //验证数字的整数位和小数位的位数是否超过指定的长度 private double money;
---日期---
@Future //必须在当前日期之后 private Date date;
@Past //必须在当前日期之前 private Date date ;
@Pattern(regexp = "[abc]") //与给定的正则相配制

自己实现自定义校验注解 

自定义的注解里必须有这几样要素
a.  String message() default "";
b.  public Class<?>[] groups() default {};
c.  Class<? extends Payload>[] payload() default {};
@Constraint(validatedBy = Xxxx.class)  指定具体的约束类(也可以为内部类) 用来实现自定义的校验规则

import javax.validation.ConstraintValidator;

import com.qbsea.mysboot2common.modlues.app.service.AppService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;


@Target({FIELD,METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {MqbStringChecker.IsMobileValidator.class})
@Inherited
@Documented
public @interface MqbStringChecker {
    String message() default "手机号不正确";
    public Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};

    @Service
    class IsMobileValidator implements ConstraintValidator<MqbStringChecker,String> {
        @Autowired
        AppService appService;

        @Override
        public boolean isValid(String value, ConstraintValidatorContext context) {
            System.out.println(appService.findBy().get());
            if(value.startsWith("150")){//测试不能能150开头的手机号
                return false;
            }
            return true;
        }
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值