1 导入必要依赖(默认已经导入springmvc的相关依赖)
<!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator -->
<!--hibernate校验器,与hibernate的数据获取无关-->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.1.2.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jboss.logging/jboss-logging -->
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.4.1.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
2 配置校验器bean于错误提示文件
配置bean
<!-- 校验器 -->
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<!-- 校验器类 -->
<property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
<!-- 指定校验使用的资源文件,如果不指定则默认使用classpath下的ValidationMessages.properties -->
<property name="validationMessageSource" ref="messageSource" />
</bean>
<!-- 校验错误信息配置文件,使用ReloadableResourceBundleMessageSource加载配置文件 -->
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath:ValidationMessages</value>
</list>
</property>
<!-- 资源文件编码格式 -->
<property name="defaultEncoding" value="UTF-8"/>
<!-- 对资源文件内容缓存时间,单位秒 -->
<property name="cacheSeconds" value="120" />
</bean>
在错误文件ValidationMessages.properties文件中编写错误提示信息
user.name.length=用户名长度必须在6到9之间
user.name.notNull=用户名不能为空
在需要校验的实体类中使用注解指定校验方式于提示信息
package com.dahuici.zyb.entity;
import lombok.Data;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@Data
public class User {
//非空校验
@NotNull(message = "{user.name.notNull}")
//字符串长度校验
@Size(min = 6,max = 9,message = "{user.name.length}")
private String name;
private Integer age;
public User(){
}
public User(String name,Integer age){
this.name = name;
this.age = age;
}
}
3 将校验器注入适配器
这里的适配器是RequestMappingHandlerAdapter,查看源码会发现该类没有校验器对应的属性,其实该校验器是注入进了适配器的WebBindingInitializer属性的validator属性里面。所以还有一种租入适配器的方式是通过WebBindingInitializer属性注入,具体注入的WebBindingInitializer实际是其实现类ConfigurableWebBindingInitializer的实例对象。
<!--自己配置映射器与适配器并注入校验器-->
<mvc:annotation-driven validator="validator">
<!--配置返回值转换器-->
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="defaultCharset" value="utf-8"></property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
4 验证
在controller里面用@Validated表示该实体需要验证,然后用BindingResult对象接受验证结果,当验证不通过时BindingResult就会接受对应的错误提示信息。
@GetMapping("/test.do")
public String helloword(@Validated User user,BindingResult bindingResult)
throws IOException
{
StringBuffer stringBuffer = new StringBuffer();
if (bindingResult.hasErrors()){
List<ObjectError> allErrors = bindingResult.getAllErrors();
allErrors.forEach(e -> stringBuffer.append(e.getDefaultMessage()));
return stringBuffer.toString();
}
return "验证成功";
}
@Validated与@Valid区别
1 @Validated可以分组验证,@Valid不能
对于实体,同一个属性对于不同的操作有不同的验证规则(例如插入与更新),这时就需要对属性的验证进行分组。
实体:
@NotNull(message = "id不能为空",groups = {Update.class})
private String id;
controller:
@PutMapping("/idtuConstructionProcess")
public ResponseEntity update(@RequestBody @Validated({Update.class}) IdtuConstructionProcess idtuConstructionProcess) {
boolean result = idtuConstructionProcessService.updateById(idtuConstructionProcess);
return new ResponseEntity(result ? ResponseEntity.SUCCESS : ResponseEntity.SERVER_ERROR, result ? "success" : "failed");
}
2 注解地方
@Validated:可以用在类、方法和方法参数上。但是不能用在成员属性(字段)上
@Valid:可以用在方法、构造函数、方法参数和成员属性(字段)上
由于@Valid可以使用在属性上,因此@Validated可以结合@Valid实现嵌套验证
3 嵌套验证
当一个实体的属性是另一个实体,例如用户实体(User)拥有一辆车(Car),希望在验证User时也对Car属性进行验证,那么就必须在Car属性前添加@Valid。添加了@Valid后就能进行嵌套验证。
提示:如果只在controller层使用@Validated注解时,可以直接在参数前面添加,类上无需添加@Validated注解,但是如果要在Controller层使用@NotNull这些注解,那么Controller类上必须添加@Validated注解才能生效。(在springboot上测试的,没有单独使用springmvc测试该功能)
常用注解
可参考这篇博客:
https://blog.csdn.net/qq_37805065/article/details/102638136