1.参数验证常用注解
@Null | 限制只能为null | |
@NotNUll | 限制必须不为null | |
@AssertFalse | 限制必须为false | |
@AssertTrue | 限制必须为true | |
@DecimalMax(value) | 限制必须为一个不大于指定值的数字 | |
@DecimalMin(value) | 限制必须为一个不小于指定的数字 | |
@Digits(integer,fraction) | 限制必须为一个小数,且整数部分的位数不能超过integer,小数部分的位数不能超过fraction | |
@Future | 限制必须是一个将来的日期 | |
@Max(value) | 限制必须为一个不大于指定值的数字 | |
@Min(value) | 限制必须为一个不小于指定值的数字 | |
@Past | 限制必须是一个过去的日期 | |
@Pattern(value) | 限制必须符合指定的正则表达式 | |
@Size(max,min) | 限制字符串长度必须在min到max之间 | |
@NotEmpty | 验证注解的元素值不为null且不为空(字符串长度不为0,集合大小不为0) | |
@NotBlank | 验证注解的元素值不为空(不为null,去除首尾空格长度为0),不同于@NotEmpty,@NotBlank只应用与字符串且在比较时会去除字符串的空格。 | |
验证注解的元素值是Email,也可以通过正则表达式和flag指定自定义的email格式 |
2.jar包版本
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.17.Final</version>
</dependency>
3.参数验证配置
import org.hibernate.validator.HibernateValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
/**
* @description: hibernate Validator服务器验证处理器
**/
@Configuration
public class ValidatorConfiguration {
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
MethodValidationPostProcessor postProcessor = new MethodValidationPostProcessor();
/**设置validator模式为快速失败返回*/
postProcessor.setValidator(validator());
// <!-- 校验器的工作模式:
// validator.fail_fast:快速失败返回模式(只要有一个验证失败,则返回异常)
// validator.normal:普通模式(会校验完所有的属性,然后返回所有的验证失败信息)
return postProcessor;
}
@Bean
public Validator validator(){
ValidatorFactory validatorFactory = Validation.byProvider( HibernateValidator.class )
.configure()
.addProperty( "hibernate.validator.fail_fast", "true" )
.buildValidatorFactory();
Validator validator = validatorFactory.getValidator();
return validator;
}
}
4.手动提交验证工具类
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.Set;
@Component
public class ValidateUtil {
/**
* 验证器
*/
@Autowired
private Validator validator ;
private static ValidateUtil validateUtil;
// 加入注解@postcontruct来初始化这个bean
@PostConstruct
public void init(){
validateUtil=this;
validateUtil.validator=this.validator;
}
/**
* 校验实体,返回实体所有属性的校验结果
*
* @param obj
* @param
* @return CommonResult
*/
public static <T> CommonResult validateEntity(T obj) {
//解析校验结果
Set<ConstraintViolation<T>> validateSet = validateUtil.validator.validate(obj, Default.class);
return buildValidationResult(validateSet);
}
/**
* 校验指定实体的指定属性是否存在异常
*
* @param obj
* @param propertyName
* @param <T>
* @return
*/
public static <T> CommonResult validateProperty(T obj, String propertyName) {
Set<ConstraintViolation<T>> validateSet = validateUtil.validator.validateProperty(obj, propertyName, Default.class);
return buildValidationResult(validateSet);
}
/**
* 将异常结果封装返回
*
* @param validateSet
* @param <T>
* @return
*/
private static <T> CommonResult buildValidationResult(Set<ConstraintViolation<T>> validateSet) {
CommonResult commonResult = new CommonResult();
if (CollectionUtils.isNotEmpty(validateSet)) {
commonResult.setCode(Constants.ERROR_CODE);
ConstraintViolation<T> constraintViolation = validateSet.iterator().next();
commonResult.setMsg("参数验证失败:" + constraintViolation.getPropertyPath().toString() + constraintViolation.getMessage());
} else {
commonResult.setCode(Constants.SUCCESS_CODE);
commonResult.setMsg("验证成功");
}
return commonResult;
}
}
5.List集合验证工具类
import lombok.Data;
import javax.validation.Valid;
import java.util.*;
/**
* list集合验证工具类
* @param <E>
*/
@Data
public class ValidateList<E> implements List<E> {
@Valid
private List<E> list = new ArrayList<>();
@Override
public int size() {
return list.size();
}
@Override
public boolean isEmpty() {
return list.isEmpty();
}
@Override
public boolean contains(Object o) {
return list.contains(o);
}
@Override
public Iterator<E> iterator() {
return list.iterator();
}
@Override
public Object[] toArray() {
return list.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return list.toArray(a);
}
@Override
public boolean add(E e) {
return list.add(e);
}
@Override
public boolean remove(Object o) {
return list.remove(o);
}
@Override
public boolean containsAll(Collection<?> c) {
return list.containsAll(c);
}
@Override
public boolean addAll(Collection<? extends E> c) {
return list.addAll(c);
}
@Override
public boolean addAll(int index, Collection<? extends E> c) {
return list.addAll(index,c);
}
@Override
public boolean removeAll(Collection<?> c) {
return list.removeAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
return list.retainAll(c);
}
@Override
public void clear() {
list.clear();
}
@Override
public E get(int index) {
return list.get(index);
}
@Override
public E set(int index, E element) {
return list.set(index,element);
}
@Override
public void add(int index, E element) {
list.add(index,element);
}
@Override
public E remove(int index) {
return list.remove(index);
}
@Override
public int indexOf(Object o) {
return list.indexOf(o);
}
@Override
public int lastIndexOf(Object o) {
return list.lastIndexOf(o);
}
@Override
public ListIterator<E> listIterator() {
return list.listIterator();
}
@Override
public ListIterator<E> listIterator(int index) {
return list.listIterator(index);
}
@Override
public List<E> subList(int fromIndex, int toIndex) {
return list.subList(fromIndex,toIndex);
}
}
6.单个对象验证例子
/**
* 传入对象参数验证模板
*
* @param vo
* @param result
* @return
* @throws Exception
*/
@RequestMapping(value = "/testValidated")
public CommonResult testValidated(@RequestBody @Validated PersonVO vo, BindingResult result) throws Exception {
CommonResult commonResult = new CommonResult();
if (result.hasFieldErrors()) {
commonResult.Result600(result.getAllErrors().get(0).getDefaultMessage());
return commonResult;
}
return CommonResult.RESULT200;
}
/**
* 传入对象参数手动验证模板
*
* @param vo
* @param result
* @return
* @throws Exception
*/
@RequestMapping(value = "/testValidated")
public CommonResult testValidatedList(@RequestBody PersonVO vo, BindingResult result) throws Exception {
CommonResult commonResult1 = ValidateUtil.validateEntity(vos);
return commonResult1;
}
7.list集合对象验证例子
/**
* 传入对象list参数验证模板
*
* @param vos
* @param result
* @return
* @throws Exception
*/
@RequestMapping(value = "/testValidatedList")
public CommonResult testValidated(@RequestBody @Validated ValidateList<PersonVO> vos, BindingResult result) throws Exception {
CommonResult commonResult = new CommonResult();
if (result.hasFieldErrors()) {
commonResult.Result600(result.getAllErrors().get(0).getDefaultMessage());
return commonResult;
}
return CommonResult.RESULT200;
}
/**
* 传入对象list参数手动验证模板
*
* @param vos
* @param result
* @return
* @throws Exception
*/
@RequestMapping(value = "/testValidatedList")
public CommonResult testValidatedList(@RequestBody ValidateList<PersonVO> vos, BindingResult result) throws Exception {
CommonResult commonResult = ValidateUtil.validateEntity(vos);
return commonResult;
}