java spring 数据校验_Spring 数据校验

引入包

org.springframework.boot:spring-boot-starter-validation

参数校验

@Getter

@Setter

@ToString

public class LoginVo {

@NotBlank

@Pattern(regexp = "\\d")

private String id;

@NotBlank

private String password;

}

获得校验结果

方法1:Errors

import org.springframework.validation.Errors;

import org.springframework.validation.ObjectError;

@PostMapping("/login")

@ResponseBody

public boolean doLogin(@Valid LoginVo vo, Errors errors) {

for (ObjectError error : errors.getAllErrors()) {

System.out.println(error);

}

if (errors.hasErrors()) {

return false;

}

return loginService.login(vo);

}

方法2:异常处理器 (推荐)

@PostMapping("/login")

@ResponseBody

public boolean doLogin(@Valid LoginVo vo) {

return loginService.login(vo);

}

@ControllerAdvice

@ResponseBody

public class GlobalExceptionHandler {

@ExceptionHandler(BindException.class)

public List validationHandler(BindException e) {

return e.getAllErrors();

}

}

可用的校验约束

javax.validation.constraints

org.hibernate.validator.constraints

自定义校验

注解

将要添加到校验字段上的约束注解

@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})

@Retention(RUNTIME)

@Documented

@Constraint(validatedBy = {MobileValidator.class})

public @interface Mobile {

boolean required() default true;

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

Class>[] groups() default {};

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

}

校验器

public class MobileValidator implements ConstraintValidator {

/**

* Pattern对象是线程安全的

* Instances of this class are immutable and are safe for use by multiple

* concurrent threads. Instances of the {@link Matcher} class are not safe for

* such use.

*

* 正则表达式来自网络

*/

private static final Pattern MOBILE_PATTERN = Pattern.compile("^(13[0-9]|14[5-9]|15[0-3,5-9]|16[2,5,6,7]|17[0-8]|18[0-9]|19[0-3,5-9])\\d{8}$");

private boolean required = false;

@Override

public void initialize(Mobile constraintAnnotation) {

this.required = constraintAnnotation.required();

}

@Override

public boolean isValid(String value, ConstraintValidatorContext context) {

return valid(value, this.required);

}

public static boolean valid(String value, boolean required) {

if (StringUtils.hasText(value)) {

var matcher = MOBILE_PATTERN.matcher(value);

return matcher.matches();

} else {

return !required;

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值