【springboot】springboot validation 参数验证、分组验证及全局统一异常处理

一、jar包添加下面其中之一即可

    <dependency>
        <groupId>org.hibernate.validator</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>根据实际情况指定版本号</version>
    </dependency>
     <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-validation</artifactId>
         <version>根据实际情况指定版本号</version>
     </dependency>
 <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
     </dependency>

因为springcloud项目已经引入spring-boot-starter-web

 

二、在实体中增加验证注解

      注意下下面的注解中的groups属性作用:当实体用于不同的场景时,在验证时需要加以区分,此时需要用到分组。

如果不需要区分使用场景,可以去掉groups属性。

如本示例中,定义了两个分组Creation, Modification用于区分在新增、修改场景下对属性做不同的数据校验

 

public class RmRegionEntity extends BaseEntity{
	private static final long serialVersionUID = -322027541582939044L;

	@NotBlank(message="区域主键不能为空!", groups = {Creation.class, Modification.class})
	private String pkRegion; //区域主键

    
    @NotNull(message="城市级别不能为空!", groups = {Creation.class, Modification.class})
    private Integer fcitygrade; //城市级别:5071省级、5072地级、5073县级
    

    
    @NotBlank(message="创建人名称不能为空!", groups = {Creation.class})
    private String creatorName; //创建人名称
    
    
    @NotBlank(message="修改人名称不能为空!", groups = {Modification.class})
    private String modifierName; //修改人名称
    


}

三、在Controller中的使用

         使用@Valid或@Validated,但当指定分组时需要使用@Validated

         下面示例中,因用到分组,所以注解中传入了Creation,表示在数据校验时校验实体中分组为Creation的属性。

          如果没用到分组,@Valid或@Validated都可以使用不用传值,直接使用即可

	@PostMapping("/v1/insertRmRegion") 
	public ResponseResult<Integer> insertRmRegion(@Validated({Creation.class}) @RequestBody RmRegionEntity rmRegionEntity) {
		ResponseResult<Integer> result = new ResponseResult<>();
		Integer count = null;
		
		try {
			count = rmRegionService.insertRmRegion(rmRegionEntity);
			
			result.responseSuccess(null, count, "新增数据成功!");
		}catch(BizException e) {
			logger.warn("业务异常", e);
			result.responseBizException(null, null, e.getMessage());
		}catch(Exception e) {
			logger.error("新增信息出现异常", e);
			result.responseException(null, null, e.getMessage());
		}
		
		return result;
	}	

四、分组定义

     定义成一个空的接口即可

public interface Creation {

}

五、全局异常处理

  如果要将校验的错误信息格式化成自己想要的格式,可以通过全局异常进行统一捕捉,然后返回错误信息。

类上增加注解@RestControllerAdvice

@RestControllerAdvice
public class GlobelExceptionAdvice {
	private static final Logger logger = LoggerFactory.getLogger(GlobelExceptionAdvice.class);

	@Autowired
	private HttpServletRequest httpServletRequest;
	/**
	 * 参数校验异常
	 *
	 * @param exception
	 * @return
	 */
	@ExceptionHandler({ MethodArgumentNotValidException.class })
	public ResponseResult<String> methodArgumentNotValid(MethodArgumentNotValidException exception) {
		ResponseResult<String> result = new ResponseResult<>();

		BindingResult bindingResult = exception.getBindingResult();
		//返回第一个错误的信息
		String defaultMessage = bindingResult.getFieldError().getDefaultMessage();
		String code = bindingResult.getFieldError().getCode();
		String field = bindingResult.getFieldError().getField();
		result.responseBizException(code, field, defaultMessage);

		logger.warn("参数验证错误,错误信息: {}, 请求的URL: {}", result, httpServletRequest.getRequestURI());

		return result;

	}
	
	/**
	 * 参数校验异常
	 *
	 * @param exception
	 * @return
	 */
	@ExceptionHandler(value = BindException.class)
	public ResponseResult<String> bindException(BindException exception) {
		ResponseResult<String> result = new ResponseResult<>();

		BindingResult bindingResult = exception.getBindingResult();
		//返回第一个错误的信息
		String defaultMessage = bindingResult.getFieldError().getDefaultMessage();
		String code = bindingResult.getFieldError().getCode();
		String field = bindingResult.getFieldError().getField();
		result.responseBizException(code, field, defaultMessage);

		logger.warn("参数验证错误,错误信息: {}, 请求的URL: {}", result, httpServletRequest.getRequestURI());

		return result;

	}
	
	/**
	 * 数据类型校验异常
	 * @param exception
	 * @return
	 */
	@ExceptionHandler(value = UnexpectedTypeException.class)
	public ResponseResult<String> unexpectedTypeException(UnexpectedTypeException exception) {
		ResponseResult<String> result = new ResponseResult<>();
		result.responseBizException(null, exception.getMessage(), "数据类型错误!");

		logger.warn("参数验证错误,错误信息: {}, 请求的URL: {}", result, httpServletRequest.getRequestURI());

		return result;

	}

属性验证注解

 

注解

适用的数据类型

说明

@AssertFalse

Boolean, boolean

验证注解的元素值是false

@AssertTrue

Boolean, boolean

验证注解的元素值是true

@DecimalMax(value=x)

BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.

验证注解的元素值小于等于@ DecimalMax指定的value值

@DecimalMin(value=x)

BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.

验证注解的元素值小于等于@ DecimalMin指定的value值

@Digits(integer=整数位数, fraction=小数位数)

BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.

验证注解的元素值的整数位数和小数位数上限

@Future

java.util.Date, java.util.Calendar; Additionally supported by HV, if theJoda Time date/time API is on the class path: any implementations ofReadablePartial andReadableInstant.

验证注解的元素值(日期类型)比当前时间晚

@Max(value=x)

BigDecimal, BigInteger, byte, short,int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type ofCharSequence (the numeric value represented by the character sequence is evaluated), any sub-type of Number.

验证注解的元素值小于等于@Max指定的value值

@Min(value=x)

BigDecimal, BigInteger, byte, short,int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of CharSequence (the numeric value represented by the char sequence is evaluated), any sub-type of Number.

验证注解的元素值大于等于@Min指定的value值

@NotNull

Any type

验证注解的元素值不是null

@Null

Any type

验证注解的元素值是null

@Past

java.util.Date, java.util.Calendar; Additionally supported by HV, if theJoda Time date/time API is on the class path: any implementations ofReadablePartial andReadableInstant.

验证注解的元素值(日期类型)比当前时间早

@Pattern(regex=正则表达式, flag=)

String. Additionally supported by HV: any sub-type of CharSequence.

验证注解的元素值与指定的正则表达式匹配

@Size(min=最小值, max=最大值)

String, Collection, Map and arrays. Additionally supported by HV: any sub-type of CharSequence.

验证注解的元素值的在min和max(包含)指定区间之内,如字符长度、集合大小

@Valid

Any non-primitive type(引用类型)

验证关联的对象,如账户对象里有一个订单对象,指定验证订单对象

@NotEmpty

CharSequence,CollectionMap and Arrays

验证注解的元素值不为null且不为空(字符串长度不为0、集合大小不为0)

@Range(min=最小值, max=最大值)

CharSequence, Collection, Map and Arrays,BigDecimal, BigInteger, CharSequence, byte, short, int, long and the respective wrappers of the primitive types

验证注解的元素值在最小值和最大值之间

@NotBlank

CharSequence

验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@NotEmpty,@NotBlank只应用于字符串且在比较时会去除字符串的空格

@Length(min=下限, max=上限)

CharSequence

验证注解的元素值长度在min和max区间内

@Email

CharSequence

验证注解的元素值是Email,也可以通过正则表达式和flag指定自定义的email格式

参考地址:

https://www.cnblogs.com/moues/p/11399421.html

https://blog.51cto.com/1197822/2467086

https://blog.csdn.net/songguopeng/article/details/98961787

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值