springboot使用validation校验类

springboot使用spring validation进行校验

spring validation相关注解校验

如何处理校验时的异常
  • 抓取 MethodArgumentNotValidExceptionBindException异常
代码实现
  • 需要校验的DTO
/**
 * 校验DTO
 *
 * @author 伍磊
 */
@Data
@ApiModel("校验DTO")
public class ValidatorDTO implements Serializable {

    private static final long serialVersionUID = -8442930023168057347L;

    @ApiModelProperty("姓名")
    @NotEmpty(message = "姓名不能为空")
    private String name;

    @ApiModelProperty("年龄")
    @Min(value = 18, message = "年龄需要大于18")
    @Max(value = 25, message = "年龄需要小于25")
    @NotNull(message = "年龄不能为空")
    private Integer age;

    @ApiModelProperty("邮箱")
    @Email(message = "请输入正确的邮箱格式")
    @NotEmpty(message = "邮箱不能为空")
    private String email;

}
  • 需要在controller层对此DTO进行校验 使用注解 @validated 即可
@PostMapping("/demo")
@ApiOperation("demo-validator")
public JsonResult demo(@RequestBody @Validated ValidatorDTO validatorDTO) {
    return JsonReturn.succ();
}
  • 使用全局的validator校验异常捕获(校验时不符合标准的话捕获此异常,再进行相关处理)
/**
 * validation异常捕获处理 (可能是MethodArgumentNotValidException或 BindException)
 * @param e  MethodArgumentNotValidException 异常
 * @return com.example.common.bean.JsonResult
 */
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public JsonResult serviceHandle(MethodArgumentNotValidException e) {
    List allErrors = e.getBindingResult().getAllErrors();
    StringBuilder stringBuilder = new StringBuilder();
    allErrors.forEach(objectError -> stringBuilder.append(objectError.getDefaultMessage()).append(";"));
    return JsonReturn.fail(stringBuilder.toString());
}
  • 自定义注解进行校验
## 自定义校验注解
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;

/**
 * 电话号码格式校验
 * @Constraint注解表明是由哪个类进行校验
 * groups和payload为必须
 * @author 伍磊
 */
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Constraint(validatedBy = {IsMobileValidator.class})
public @interface IsMobile {

    /**
     * 是否需要校验
     * @return  boolean
     */
    boolean required() default true;

    String message() default "手机号码格式错误";

    Class[] groups() default { };

    Class[] payload() default { };
}

## ------------------------------------------------------------

## 自定义校验注解解析器
import com.leiwu.study.spikecommon.utils.tools.ValidatorUtils;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * isMobile注解校验代码
 *
 * @author 伍磊
 */
public class IsMobileValidator implements ConstraintValidator {
    private boolean required = false;

    @Override
    public void initialize(IsMobile constraintAnnotation) {
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        // value为空时进行校验
        if (StringUtils.isBlank(value)) {
            if (required) {
                return false;
            }
            return true;
        } else {
            // 不为空时进行校验
            return ValidatorUtils.isMobile(value);
        }
    }
}

## ------------------------------------------------------------

## 校验工具类(手机号码)
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 校验类
 *
 * @author 伍磊
 */
public class ValidatorUtils {

    /**
     * 校验手机号码格式是否正确
     * @param mobile  需要校验的手机号码
     * @return  boolean
     */
    public static boolean isMobile(String mobile) {
        String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0,5-9]))\\d{8}$";
        if (mobile.length() != 11) {
            return false;
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(mobile);
            boolean isMatch = m.matches();
            if (isMatch) {
                return true;
            } else {
                return false;
            }
        }
    }
}

## ------------------------------------------------------------

## 使用此注解
@IsMobile()
private String phone;

你可能感兴趣的:(springboot使用validation校验类)