spring数据校验

news/2025/3/20 6:01:03/

数据校验

概述

在开发中,会存在参数校验的情况,如:注册时,校验用户名不能为空、用户名长度不超过20个字符,手机号格式合法等。如果使用普通方式,会将校验代码和处理逻辑耦合在一起,在需要新增一种校验时,也需要修改很多地方。

spring validation允许通过注解的方式来定义校验规则,把校验和业务分离开。它其实就是对Hibernate Validation进一步的封装。

spring中的校验方式

  • 通过实现org.springframework.validation.Validator接口,然后在代码中调用这个类。
  • 按照Bean Validation方式进行校验(通过注解方式)。
  • 基于方法实现校验。

通过Validator接口实现校验

实现步骤

1、依赖引入
<dependency><groupId>org.hibernate.validator</groupId><artifactId>hibernate-validator</artifactId><version>8.0.1.Final</version>
</dependency><dependency><groupId>org.glassfish</groupId><artifactId>jakarta.el</artifactId><version>5.0.0-M1</version>
</dependency>
2、创建实体类
public class Person {private String name;private Integer age;public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}
}
3、编写校验类
public class PersonValidator implements Validator {/*** 此方法用来表示此校验用在哪个类型上* @param clazz* @return*/@Overridepublic boolean supports(Class<?> clazz) {return Person.class.equals(clazz);}/*** 此方法是设置校验逻辑的地点,其中ValidatorUtils,是Spring封装的工具类。帮助快速实现校验* @param target* @param errors*///校验规则@Overridepublic void validate(Object target, Errors errors) {//name不能为空ValidationUtils.rejectIfEmpty(errors, "name", "name Empty", "name is null");//age不能小于0,不能大于200Person p = (Person)target;if (p.getAge() <= 0){errors.rejectValue("age", "age.value.error", "age<0");} else if (p.getAge() >= 200) {errors.rejectValue("age", "age.value.error.max", "age>200");}}
}
4、测试
@Test
public void testValidation(){//创建Person对象Person person = new Person();person.setAge(30);person.setName(null);//创建person对应对象DataBinder binder = new DataBinder(person);//设置校验器binder.setValidator(new PersonValidator());//调用方法、执行校验binder.validate();//输出校验结果BindingResult result = binder.getBindingResult();System.out.println("result.getAllErrors() = " + result.getAllErrors());
}
/*
* Empty.name,name Empty.java.lang.String,name Empty]; arguments []; default message [name is null]]
* */

Bean Validation注解实现

使用Bean Validation校验方式,需要使用到javax.validation.ValidatorFactoryjavax.validation.Validator注入到容器中,spring默认有一个实现类LocalValidatorFacoryBean,它实现了上面Bean Validation中的接口,并且也实现了org.springframeworkvalidation.Validator接口。

实现步骤

1、创建配置类,配置LocalValidatorFactoryBean
@Configuration
@ComponentScan("com.louis.testvalidationtwo")
public class ValidationConfig {@Beanpublic LocalValidatorFactoryBean validator(){return new LocalValidatorFactoryBean();}
}
2、创建实体类

定义属性,生成get、set方法,在属性上面使用注解设置校验规则。

public class User {@NotNullprivate String name;@Min(0)@Max(200)private int age;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}
}
3、创建校验器

①使用原生的校验器

@Service
public class MyValidationOne {//使用原生的校验器@Autowiredprivate Validator validator;public boolean testValidator(User user){Set<ConstraintViolation<User>> validate = validator.validate(user);return validate.isEmpty();}

②使用spring中的validation

@Service
public class MyValidationTwo {//使用spring中的validation@Autowiredprivate Validator validator;public List testValidatorTwo(User user){BindException bindException = new BindException(user, user.getName());validator.validate(user, bindException);List<ObjectError> allErrors = bindException.getAllErrors();return allErrors;}
}
4、测试

使用方式①

@Test
public void testValidator(){ApplicationContext context = new AnnotationConfigApplicationContext(ValidationConfig.class);MyValidationOne validationOne = context.getBean(MyValidationOne.class);User user = new User();boolean result = validationOne.testValidator(user);System.out.println("result = " + result);/*result = false*/
}

使用方式②

@Test
public void testValidatorTwo(){ApplicationContext context = new AnnotationConfigApplicationContext(ValidationConfig.class);MyValidationTwo validationTwo = context.getBean(MyValidationTwo.class);User user = new User();List result = validationTwo.testValidatorTwo(user);System.out.println("result = " + result);/*Object name must not be null*/
}

常用注解

注解说明
@NotNull限制必须不为空
@NotEmpty只作用于字符串类型,字符串不为空,且长度不为0
@NotBlank 只作用于字符串类型,字符串不为空且trim()后也并不为空
@DecimalMax(value)限制必须为一个不大于指定值的数字,小数存在精度
@DecimalMin(value)限制必须为一个不小于指定值的数字,小数存在精度
@Max(value)限制必须为一个不大于指定值的数字
@Min(value)限制必须为一个不小于指定值的数字
@Pattern(value)限制必须符合指定的正则表达式
@Size(max, min)限制字符串长度必须在min到max之间
@Email验证注解的元素值是Email,也可以通过正则表达式和flag指定自定义的email格式

基于方法实现校验

实现步骤

1、创建配置类
@Configuration
@ComponentScan("com.louis.validationbymethod")
public class ValidationConfig {@Beanpublic MethodValidationPostProcessor validationPostProcessor(){return new MethodValidationPostProcessor();}
}
2、创建实体类

使用注解设置校验规则

public class User {@NotNullprivate String name;@Max(200)@Min(0)private int age;@NotBlank(message = "手机号不能为空")@Pattern(regexp = "^1(3|4|5|7|8)\\d{9}$", message = "手机号格式错误")private String phone;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}
}
3、编写校验器
@Service
@Validated
public class MyService {public String testMethod(@NotNull @Valid User user){return user.toString();}
}
4、测试
@Test
public void testValidationByMethod(){ApplicationContext context = new AnnotationConfigApplicationContext(ValidationConfig.class);MyService service = context.getBean(MyService.class);service.testMethod(new User());/*testMethod.arg0.phone: 手机号不能为空, testMethod.arg0.name: 不能为null*/
}

实现自定义校验

实现步骤

1、自定义校验注解

@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = {CannotHaveBlankValidator.class})//表示指定校验器的类,实现真正的校验器规则
public @interface CannotHaveBlank {//默认的出现错误的提示信息String message() default "不能包含空格";Class<?>[] groups() default {};Class<? extends Payload>[] payload() default {};@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface List {CannotHaveBlank[] value();}
}

2、编写校验规则

public class CannotHaveBlankValidator implements ConstraintValidator<CannotHaveBlank, String> {@Overridepublic boolean isValid(String value, ConstraintValidatorContext context) {if(value != null &&value.contains(" ")){//获取默认提示信息String defaultConstraintMessageTemplate = context.getDefaultConstraintMessageTemplate();System.out.println("default message:"+defaultConstraintMessageTemplate);//禁用默认提示信息context.disableDefaultConstraintViolation();//设置提示语context.buildConstraintViolationWithTemplate("can not constrains blank").addConstraintViolation();return false;}return false;}
}

3、创建实体类

public class User {@NotNullprivate String name;@Max(200)@Min(0)private int age;@NotBlank(message = "手机号不能为空")@Pattern(regexp = "^1(3|4|5|7|8)\\d{9}$", message = "手机号格式错误")private String phone;@CannotHaveBlankprivate String message;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}
}

4、测试

//使用基于方法实现校验的校验器
public class TestValidationByMethod {@Testpublic void testValidationByMethod(){ApplicationContext context = new AnnotationConfigApplicationContext(ValidationConfig.class);MyService service = context.getBean(MyService.class);User user = new User();user.setAge(30);user.setName("Louie");user.setPhone("18111111111");user.setMessage("L o u i s");service.testMethod(user);
/*default message:不能包含空格
jakarta.validation.ConstraintViolationException: testMethod.arg0.message: can not constrains blank*/}
}

http://www.ppmy.cn/news/980972.html

相关文章

2023杭电多校第三场 1012.Noblesse Code

传送门:Vjudge 前题提要:一道挺有意思的数论题.赛时对于这道题没什么想法,但是赛后细品之后其实感觉也就那么一回事.但是这种 更相损减术与辗转相除法 相转化的题目还是有点典的,需要好好消化一下. 首先看完题目.我们需要考虑的是 ( A , B ) (A,B) (A,B)与 ( a , b ) (a,b) (…

线程的控制

一、线程中断常用方法 setName //设置线程名称&#xff0c;使之与参数name相同getName //返回该线程的名称start //使该线程开始执行&#xff1b;java虚拟机底层调用该线程的start()方法run //调用线程对象的run方法setPriority //更改线程的优先级getPriority //获取线程的优…

Beamer学习手册

Beamer学习手册 ZJU Beamer模板解读参考链接 谨以本文记录一下学习beamer的过程 本文基于 Overleaf 的 ZJU Beamer模板 进行学习并修改模板&#xff0c;感谢前辈的贡献&#xff01; ZJU Beamer模板解读 首先在 Overleaf 下载 ZJU Beamer模板 &#xff0c;解压压缩包后&#xf…

IO进程线程day2(2023.7.26)

一、Xmind整理&#xff1a; 二、课上练习&#xff1a; 练习1&#xff1a;全缓冲 //由于编译器优化&#xff0c;只打开不操作&#xff0c;此时不会真正申请缓冲区。 fputc(a, fp); printf("%ld\n", fp->_IO_buf_end - fp->_IO_buf_base ); 刷新条件&#xff…

VRRP技术和浮动路由(第二十六课)

VRRP技术和浮动路由(第二十六课) 一、浮动路由 1、浮动路由概述 1&#xff09;浮动路由是什么 -浮动路由又称为路由备份&#xff0c;由两条或多条链路组成浮动路由 -浮动路由指配置两条静态路由&#xff0c;这两条静态路由的目的地址相同&#xff0c;但是下一跳地址不同两…

学习笔记--TCP/IP协议

TCP/IP协议 TCP (Transmission Control Protocol)传输控制协议&#xff0c;传输层协议。 一、协议的分层 ISO网络层分为7层 二、分层的作用 具体通信情况&#xff1a; 三、报文传输 三次握手连接&#xff0c;四次挥手释放 参考链接&#xff1a; https://zhuanlan.zhih…

Java 强制类型转换原理(父类转子类、子类转父类)

在Java中&#xff0c;对象的强制转换&#xff08;也称为类型转换&#xff09;是将一个对象的引用转换为另一个类的引用&#xff0c;前提是这两个类之间存在继承或实现关系。强制转换可能会导致运行时异常&#xff0c;因为在转换的过程中&#xff0c;如果对象的实际类型与转换的…

图为科技T501赋能工业机器人 革新传统工业流程

工业机器人已成为一个国家制造技术与科技水平的重要衡量标准&#xff0c;在2019年&#xff0c;中国工业机器人的组装量与产量均位居了全球首位。 当前&#xff0c;工业机器人被广泛用于电子、物流、化工等多个领域之中&#xff0c;是一种通过电子科技和机械关节制作出来的智能机…