validation 验证参数

2024-06-22 08:52
文章标签 参数 验证 validation

本文主要是介绍validation 验证参数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

validation 验证参数

一、引入POM依赖

添加spring-boot-starter-validation
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId>
</dependency>
或添加hibernate-validator
<dependency><groupId>org.hibernate.validator</groupId><artifactId>hibernate-validator</artifactId>
</dependency>
或添加spring-boot-starter-web
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>

二、校验注解

JSR提供的校验注解:
  1. @Null:被注释的元素值必须为null。
  2. @NotNull:被注释的元素值必须不为null。
  3. @Pattern(regex=):被注释的元素字符串必须符合指定的正则表达式。
  4. @Size(max=, min=):集合元素数量必须在min和max范围内。
  5. @AssertTrue:被注释的元素必须为true。
  6. @AssertFalse:被注释的元素必须为false。
  7. @Min(value):被注释的元素必须是一个数字,其值必须大于等于指定的最小值。
  8. @Max(value):被注释的元素必须是一个数字,其值必须小于等于指定的最大值。
  9. @Range(min,max):数字必须在min和max范围内。
  10. @DecimalMin(value):被注释的元素必须是一个数字,其值必须大于等于指定的最小值。
  11. @DecimalMax(value):被注释的元素必须是一个数字,其值必须小于等于指定的最大值。
  12. @Digits (integer, fraction):被注释的元素必须是一个数字,其值必须在可接受的范围内。
  13. @Past:被注释的元素必须是一个过去的日期。
  14. @Future:被注释的元素必须是一个将来的日期。
  15. @Email:字符串必须是Email地址。
  16. @SafeHtml:字符串必须是安全的html。
  17. @URL:字符串必须是合法的URL。
  18. @CreditCardNumber(ignoreNonDigitCharacters=):字符串必须是信用卡号,按照美国的标准验证。
  19. @Size(max,min):限制字符长度必须在min到max之间。
Hibernate Validator提供的校验注解:
  1. @NotBlank(message =):验证字符串非null,且trim后长度必须大于0。
  2. @Length(min=,max=):被注释的字符串的大小必须在指定的范围内。
  3. @NotEmpty:被注释的字符串的必须非空。
  4. @Range(min=,max=,message=):被注释的元素必须在合适的范围内。
  5. @AssertFalse:校验false。
  6. @AssertTrue:校验true。
  7. @DecimalMax(value=,inclusive=):小于等于value,inclusive=true是小于等于。
  8. @DecimalMin(value=,inclusive=):与上类似。
  9. @Max(value=):小于等于value。
  10. @Min(value=):大于等于value。
  11. @NotNull:检查Null。
  12. @Past:检查日期。
  13. @Pattern(regex=,flag=):正则。
  14. @Size(min=, max=):字符串,集合,map限制大小。
  15. @Valid:对po实体类进行校验。

三、常用注解的使用

Controller添加@Valid或者@Validated都可以
@RestController
@RequestMapping("/")
public class DemoController {@RequestMapping("test")public String test(@Valid @RequestBody request request) {}
}
@Pattern @NotBlank
//正则: 手机号格式是否正确
public static final String REGEX_PHONE = "(^$)|(^[1][3-9][0-9]{9}$)";@Pattern(regexp = Constants.REGEX_PHONE, message = "借款人手机号格式不正确")
@NotBlank(message = "借款人手机号不能为空")
@ApiModelProperty("借款人手机号")
private String borrowerPhone;
@Pattern(regexp = "[ABCD]", message = "权利取得方式不正确")
@ApiModelProperty("权利取得方式(原始:A,继承:B,承受:C,其他:D)")
@NotBlank(message = "权利取得方式不能为空")
private String acqMode;
@Pattern(regexp = "agree|disagree", message = "分发权利不正确")
@ApiModelProperty("分发权利(agree:同意分发,disagree:不同意分发)")
private String copyrightDispense;
@Past
@Past(message = "首次发表日期不正确")
@ApiModelProperty("首次发表日期")
@NotBlank(message = "首次发表日期不能为空")
private String publishDate;
@Size @Empty
@Empty(message = "字体文件数量不能为空")
@Size(max = 50, message = "字体文件数量过多")
@ApiModelProperty("字体文件")
private List<Long> fontFile;
@Length
@Length(max = 20, message = "企业法人名称过长")
@ApiModelProperty("企业法人名称")
private String legalName;
@Range
@Range(min=0,max=2,message="非法性别")
private String sex;
@Email
@Email(message="非法邮件地址")
private String email;
@Min @Max
@Min(value = 1, message = "作品是否涉及字体1-4以内整数")
@Max(value = 4, message = "作品是否涉及字体1-4以内整数")
@ApiModelProperty("作品是否涉及字体")
private Integer isHasFont;

四、分组校验

public class ValidationGroups {public interface ValidA {}public interface ValidB {}
}@ApiModelProperty("身份证背面id")
@NotNull(message = "身份证背面id不能为空", groups = {ValidationGroups.ValidA.class,ValidationGroups.ValidB.class})
private Long backAttachId;@ApiModelProperty("证件id")
@NotNull(message = "证件id不能为空", groups = ValidationGroups.ValidB.class)
private Long businessAttachId;//注解传参校验
public ResultVo<String> addOrUpdateOwnerTemplate(
@Validated(value = {ValidationGroups.ValidA.class,ValidationGroups.ValidB.class}) @NotNull OwnerTemplateReq ownerTemplateReq) throws Exception {return ownerTemplateService.addOrUpdateOwnerTemplate(ownerTemplateReq);
}//手写代码校验
if (条件) {beanValidate(ownerTemplateReq, ValidationGroups.ValidA.class);
} else {beanValidate(ownerTemplateReq, ValidationGroups.ValidB.class);
}//校验方法
private static <T> void beanValidate(T object, Class<?>... groups) throws ValidationException {Validator validator = Validation.buildDefaultValidatorFactory().getValidator();Set<ConstraintViolation<T>> validate1 = validator.validate(object);if (Objects.nonNull(validate1) && validate1.size() > 0) {String msg = validate1.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining("|"));throw new ServiceException(msg);}Set<ConstraintViolation<T>> validate = validator.validate(object, groups);if (Objects.nonNull(validate) && validate.size() > 0) {String msg = validate.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining("|"));throw new ServiceException(msg);}
}

五、@Validated @Valid

@Validated和@Valid都是Java中用于数据校验的注解,它们通常与Java Bean Validation(JSR 303)规范一起使用。在Spring框架中,可以使用这两个注解对方法参数进行校验。

  1. @Validated:这个注解用于类级别,表示该类中的所有方法都会进行数据校验。它主要用于分组校验,可以将不同的校验规则应用到不同的组上。
  2. @Valid:这个注解用于方法参数级别,表示对该参数进行数据校验。当请求中的参数不满足校验规则时,会抛出MethodArgumentNotValidException异常。例如:
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;@RestController
@Validated
public class UserController {@PostMapping("/user")public String createUser(@Valid @RequestBody User user) {// 保存用户信息return "success";}
}    

在这个例子中,createUser方法接收一个User对象作为参数,并使用@Valid注解对其进行校验。如果请求中的User对象不满足校验规则,会抛出MethodArgumentNotValidException异常。

六、全局异常处理ConstraintViolationException

import com.fa.notary.common.enums.base.ErrorCode;
import com.fa.notary.vo.ResultVo;
import io.netty.util.internal.ThrowableUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.text.MessageFormat;
import java.util.List;
import java.util.Set;@RestControllerAdvice
@Log4j2
public class GlobalExceptionHandler {/*** 处理所有不可知的异常*/@ExceptionHandler(Throwable.class)public ResultVo handleException(Throwable e){//DuplicateKeyException(唯一索引重复)if (e instanceof DuplicateKeyException) {return  ResultVo.error(ErrorCode.ERROR,"请勿重复添加");}//ServiceExceptionif(e instanceof ServiceException){return  ResultVo.error(ErrorCode.ERROR,((ServiceException) e).getMsg());}//ServiceExceptionif(e instanceof RetryException){return  ResultVo.error(ErrorCode.ERROR,((RetryException) e).getMsg());}//MissingServletRequestParameterExceptionif(e instanceof MissingServletRequestParameterException){String msg = MessageFormat.format("缺少参数{0}", ((MissingServletRequestParameterException) e).getParameterName());return  ResultVo.error(ErrorCode.ILLEGAL_PARAMETER,msg);}//ConstraintViolationExceptionif(e instanceof ConstraintViolationException){// 单个参数校验异常String msg="";Set<ConstraintViolation<?>> sets = ((ConstraintViolationException) e).getConstraintViolations();if(CollectionUtils.isNotEmpty(sets)){StringBuilder sb = new StringBuilder();sets.forEach(error -> {if (error instanceof FieldError) {sb.append(((FieldError)error).getField()).append(":");}sb.append(error.getMessage()).append(";");});msg = sb.toString();msg = StringUtils.substring(msg, 0, msg.length() -1);}return ResultVo.error(ErrorCode.ILLEGAL_PARAMETER,msg);}//BindExceptionif (e instanceof BindException){// get请求的对象参数校验异常String msg ="";List<ObjectError> errors = ((BindException) e).getBindingResult().getAllErrors();msg = getValidExceptionMsg(errors);return ResultVo.error(ErrorCode.ILLEGAL_PARAMETER,msg);}//MethodArgumentNotValidExceptionif (e instanceof MethodArgumentNotValidException){// post请求的对象参数校验异常String msg="";List<ObjectError> errors = ((MethodArgumentNotValidException) e).getBindingResult().getAllErrors();msg = getValidExceptionMsg(errors);return ResultVo.error(ErrorCode.ILLEGAL_PARAMETER,msg);}// 打印堆栈信息log.error(ThrowableUtil.stackTraceToString(e));return ResultVo.error(ErrorCode.ERROR,"网络繁忙,请稍后再试");}private String getValidExceptionMsg(List<ObjectError> errors) {if(CollectionUtils.isNotEmpty(errors)){StringBuilder sb = new StringBuilder();errors.forEach(error -> {if (error instanceof FieldError) {sb.append(((FieldError)error).getField()).append(":");}sb.append(error.getDefaultMessage()).append(";");});String msg = sb.toString();msg = StringUtils.substring(msg, 0, msg.length() -1);return msg;}return null;}
}

这篇关于validation 验证参数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1083824

相关文章

SpringBoot 获取请求参数的常用注解及用法

《SpringBoot获取请求参数的常用注解及用法》SpringBoot通过@RequestParam、@PathVariable等注解支持从HTTP请求中获取参数,涵盖查询、路径、请求体、头、C... 目录SpringBoot 提供了多种注解来方便地从 HTTP 请求中获取参数以下是主要的注解及其用法:1

HTTP 与 SpringBoot 参数提交与接收协议方式

《HTTP与SpringBoot参数提交与接收协议方式》HTTP参数提交方式包括URL查询、表单、JSON/XML、路径变量、头部、Cookie、GraphQL、WebSocket和SSE,依据... 目录HTTP 协议支持多种参数提交方式,主要取决于请求方法(Method)和内容类型(Content-Ty

python中的显式声明类型参数使用方式

《python中的显式声明类型参数使用方式》文章探讨了Python3.10+版本中类型注解的使用,指出FastAPI官方示例强调显式声明参数类型,通过|操作符替代Union/Optional,可提升代... 目录背景python函数显式声明的类型汇总基本类型集合类型Optional and Union(py

Go语言使用Gin处理路由参数和查询参数

《Go语言使用Gin处理路由参数和查询参数》在WebAPI开发中,处理路由参数(PathParameter)和查询参数(QueryParameter)是非常常见的需求,下面我们就来看看Go语言... 目录一、路由参数 vs 查询参数二、Gin 获取路由参数和查询参数三、示例代码四、运行与测试1. 测试编程路

Python lambda函数(匿名函数)、参数类型与递归全解析

《Pythonlambda函数(匿名函数)、参数类型与递归全解析》本文详解Python中lambda匿名函数、灵活参数类型和递归函数三大进阶特性,分别介绍其定义、应用场景及注意事项,助力编写简洁高效... 目录一、lambda 匿名函数:简洁的单行函数1. lambda 的定义与基本用法2. lambda

MySQL 主从复制部署及验证(示例详解)

《MySQL主从复制部署及验证(示例详解)》本文介绍MySQL主从复制部署步骤及学校管理数据库创建脚本,包含表结构设计、示例数据插入和查询语句,用于验证主从同步功能,感兴趣的朋友一起看看吧... 目录mysql 主从复制部署指南部署步骤1.环境准备2. 主服务器配置3. 创建复制用户4. 获取主服务器状态5

Spring Boot spring-boot-maven-plugin 参数配置详解(最新推荐)

《SpringBootspring-boot-maven-plugin参数配置详解(最新推荐)》文章介绍了SpringBootMaven插件的5个核心目标(repackage、run、start... 目录一 spring-boot-maven-plugin 插件的5个Goals二 应用场景1 重新打包应用

Java通过驱动包(jar包)连接MySQL数据库的步骤总结及验证方式

《Java通过驱动包(jar包)连接MySQL数据库的步骤总结及验证方式》本文详细介绍如何使用Java通过JDBC连接MySQL数据库,包括下载驱动、配置Eclipse环境、检测数据库连接等关键步骤,... 目录一、下载驱动包二、放jar包三、检测数据库连接JavaJava 如何使用 JDBC 连接 mys

Java内存分配与JVM参数详解(推荐)

《Java内存分配与JVM参数详解(推荐)》本文详解JVM内存结构与参数调整,涵盖堆分代、元空间、GC选择及优化策略,帮助开发者提升性能、避免内存泄漏,本文给大家介绍Java内存分配与JVM参数详解,... 目录引言JVM内存结构JVM参数概述堆内存分配年轻代与老年代调整堆内存大小调整年轻代与老年代比例元空

Spring Security中用户名和密码的验证完整流程

《SpringSecurity中用户名和密码的验证完整流程》本文给大家介绍SpringSecurity中用户名和密码的验证完整流程,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定... 首先创建了一个UsernamePasswordAuthenticationTChina编程oken对象,这是S