spring-boot-starter-validation 野性酷女 2022-08-29 10:53 27阅读 0赞 ## 1.验证配置 ## ### 1.1pom引用 ### <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> <version>2.2.1.RELEASE</version> </dependency> ### 1.2全局统一处理异常 ### * 当某些约束变形时,hibernate实体管理器抛出ConstraintViolationException,这意味着你违反了你正在使用的某个实体中的某些字段。 @ControllerAdvice @ResponseBody @Slf4j public class GlobalExceptionHandler { @ExceptionHandler(ConstraintViolationException.class) public ResponseMessage<Object> constraintViolationExceptionHandler(HttpServletResponse response, ConstraintViolationException ex) { response.setStatus(500); log.error("校验错误", ex); StringBuffer sb=new StringBuffer(); for (ConstraintViolation<?> constraintViolation : ex.getConstraintViolations()) { sb.append(constraintViolation.getMessage()); } return ResponseMessage.error(sb.toString()); } } * 使用@Valid时,您正在应用模型类字段中定义的验证,而您可以选择不同类型的验证,如@NotNull,@ Max,@ Min等,您将获得匹配类型。但总的来说,所有这些都与**MethodArgumentNotValidException**并行,它将在所有情况下抛出 @ControllerAdvice @ResponseBody @Slf4j public class GlobalExceptionHandler { @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseMessage<Object> constraintViolationExceptionHandler(HttpServletResponse response, MethodArgumentNotValidException ex) { response.setStatus(500); log.error("校验错误", ex); StringBuilder sb = new StringBuilder(); List<ObjectError> allErrors = ex.getBindingResult().getAllErrors(); for (ObjectError allError : allErrors) { sb.append(allError.getDefaultMessage()); } return ResponseMessage.error(sb.toString()); } } ### 1.3校验模式配置 ### 默认会校验所有属性,然后将所有错误信息一起返回,而实际使用时,一个校验失败就可以返回了。需要做如下配置 import org.hibernate.validator.HibernateValidator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; @Configuration public class ValidatorConfig { @Bean public Validator validator(){ ValidatorFactory validatorFactory= Validation.byProvider(HibernateValidator.class) .configure() .failFast(true) .buildValidatorFactory(); return validatorFactory.getValidator(); } } ## 2.使用 ## ### 1.创建实体类 ### 创建实体类,并在相对应的属性上加上约束条件。 import javax.validation.constraints.NotNull; import lombok.Data; @Data public class TestDemo { /** * 人员编号 */ @NotNull(message = "人员编号不能为空!") private String userCode; /** * 人员名称 */ @NotNull(message = "人员名称不能为空!") private String username; } ### 2.开启验证 ### #### 2.1 单个添加 #### 在需要验证的地方加上`@Valid`注解表示需要验证 * controller层 import javax.validation.Valid; @PostMapping("addOne") public ResponseMessage<Object> addUser(@RequestBody @Valid TestDemo testDemo) { return testService.add(testDemo); } #### 2.2 批量添加 #### 批量添加时,按照上述方式在list前面直接加注解会失效,不会去验证,需要包装下; * controller层 import javax.validation.Valid; @PostMapping("addBatch") public ResponseMessage<Object> addPersonInfo(@RequestBody @Valid ValidateList<TestDemo> testDemo) { return testService.addBatch(testDemo.getList()); } * ValidateList类 import javax.validation.Valid; import javax.validation.constraints.NotEmpty; import java.util.*; public class ValidateList<E> implements List<E> { @NotEmpty @Valid private List<E> list; public ValidateList() { this.list = new ArrayList<>(); } public ValidateList(List<E> list) { this.list = list; } public List<E> getList() { return list; } public void setList(List<E> list) { this.list = list; } @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(c); } @Override public boolean removeAll(Collection<?> c) { return list.removeAll(c); } @Override public boolean retainAll(Collection<?> c) { return list.removeAll(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(); } @Override public List<E> subList(int fromIndex, int toIndex) { return list.subList(fromIndex,toIndex); } } ## 参考文献 ## [1.使用spring validation完成数据后端校验-自定义校验的注解-判断是否为空][1._spring validation_-_-] [2.springboot 参数校验][2.springboot] [3.ConstraintViolationException和MethodArgumentNotValidException之间的区别是什么][3.ConstraintViolationException_MethodArgumentNotValidException] [4.解决@Valid List 无法校验的问题][4._Valid List] [1._spring validation_-_-]: https://blog.csdn.net/qb170217/article/details/81232945### [2.springboot]: https://www.cnblogs.com/cjsblog/p/8946768.html [3.ConstraintViolationException_MethodArgumentNotValidException]: https://xbuba.com/questions/57010688 [4._Valid List]: https://blog.csdn.net/wangjiangongchn/article/details/86481729?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.control
还没有评论,来说两句吧...