SpringBoot参数校验和自定义异常如何实现?

2026-04-12 16:441阅读0评论SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计1008个文字,预计阅读时间需要5分钟。

SpringBoot参数校验和自定义异常如何实现?

1. 引入依赖xml org.springframework.boot spring-boot-starter-validation 2.3.12.RELEASE

1.导入依赖

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> <version>2.3.12.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </exclusions>

2.@Validated注解的使用

实体类

//规则名称 @NotBlank(message = "规则名称不能为空") private String ruleName;

对外服务类

@RestController @Validated @RequestMapping("/alarm/globalRule") public class AlarmGlobalRuleController { @Resource private AlarmGlobalRuleService ruleService; /** * 保存规则 * * @param rule 规则 * @return {@link ResultMap} */ @PostMapping("/saveRule") public ResultMap addRule(@RequestBody @Validated AlarmGlobalRule rule){ boolean flag=ruleService.saveRule(rule); return flag ? ResultMap.ok("保存成功") : ResultMap.error("保存失败"); } /** * 删除规则 * * @param id id * @return {@link ResultMap} */ @DeleteMapping("/deleteRule") public ResultMap deleteRule(@NotBlank(message = "ID不能为空") String id){ boolean flag=ruleService.deleteRule(id); return flag ? ResultMap.ok("删除成功") : ResultMap.error("删除失败"); } }

若参数为实体,则在参数前加注解@Validated即可;

若参数为字符串,则在方法上加注解@Validated,并在字符串参数前指定校验规则;

3.自定义异常返回

@Slf4j @ControllerAdvice public class GlobalExceptionHandler { private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class); /** * 处理Validated校验异常 * <p> * 注: 常见的ConstraintViolationException异常, 也属于ValidationException异常 * * @param e * 捕获到的异常 * @return 返回给前端的data */ @ResponseStatus(code = HttpStatus.BAD_REQUEST) @ResponseBody @ExceptionHandler(value = {BindException.class, ValidationException.class, MethodArgumentNotValidException.class}) public ResultMap handleParameterVerificationException(Exception e) { String msg = null; if (e instanceof MethodArgumentNotValidException) { BindingResult bindingResult = ((MethodArgumentNotValidException) e).getBindingResult(); FieldError fieldError = bindingResult.getFieldError(); if (fieldError != null) { msg = fieldError.getDefaultMessage(); } } else if (e instanceof BindException) { FieldError fieldError = ((BindException) e).getFieldError(); if (fieldError != null) { msg = fieldError.getDefaultMessage(); } } else if (e instanceof ConstraintViolationException) { /* * ConstraintViolationException的e.getMessage()形如 * {方法名}.{参数名}: {message} * 这里只需要取后面的message即可 */ msg = e.getMessage(); if (msg != null) { int lastIndex = msg.lastIndexOf(':'); if (lastIndex >= 0) { msg = msg.substring(lastIndex + 1).trim(); } } } else { msg = "处理参数时异常"; } return ResultMap.error(ExceptionEnum.PARAMS_ERROR.getResultCode(),msg); } }

4.异常返回示例

{ "success": false, "msg": "ID不能为空", "data": null, "code": "10001" }

5.规则注解示例


限制


说明

@Null

限制只能为null

@NotNull

限制必须不为null

@AssertFalse

限制必须为false

@AssertTrue

限制必须为true

@DecimalMax(value)

限制必须为一个不大于指定值的数字

SpringBoot参数校验和自定义异常如何实现?

@DecimalMin(value)

限制必须为一个不小于指定值的数字

@Digits(integer,fraction)

限制必须为一个小数,且整数部分的位数不能超过integer,小数部分的位数不能超过fraction

@Future

限制必须是一个将来的日期

@Max(value)

限制必须为一个不大于指定值的数字

@Min(value)

限制必须为一个不小于指定值的数字

@Past

限制必须是一个过去的日期

@Pattern(value)

限制必须符合指定的正则表达式

@Size(max,min)

限制字符长度必须在min到max之间

@Past

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

@NotEmpty

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

@NotBlank

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

@Email

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

本文共计1008个文字,预计阅读时间需要5分钟。

SpringBoot参数校验和自定义异常如何实现?

1. 引入依赖xml org.springframework.boot spring-boot-starter-validation 2.3.12.RELEASE

1.导入依赖

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> <version>2.3.12.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </exclusions>

2.@Validated注解的使用

实体类

//规则名称 @NotBlank(message = "规则名称不能为空") private String ruleName;

对外服务类

@RestController @Validated @RequestMapping("/alarm/globalRule") public class AlarmGlobalRuleController { @Resource private AlarmGlobalRuleService ruleService; /** * 保存规则 * * @param rule 规则 * @return {@link ResultMap} */ @PostMapping("/saveRule") public ResultMap addRule(@RequestBody @Validated AlarmGlobalRule rule){ boolean flag=ruleService.saveRule(rule); return flag ? ResultMap.ok("保存成功") : ResultMap.error("保存失败"); } /** * 删除规则 * * @param id id * @return {@link ResultMap} */ @DeleteMapping("/deleteRule") public ResultMap deleteRule(@NotBlank(message = "ID不能为空") String id){ boolean flag=ruleService.deleteRule(id); return flag ? ResultMap.ok("删除成功") : ResultMap.error("删除失败"); } }

若参数为实体,则在参数前加注解@Validated即可;

若参数为字符串,则在方法上加注解@Validated,并在字符串参数前指定校验规则;

3.自定义异常返回

@Slf4j @ControllerAdvice public class GlobalExceptionHandler { private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class); /** * 处理Validated校验异常 * <p> * 注: 常见的ConstraintViolationException异常, 也属于ValidationException异常 * * @param e * 捕获到的异常 * @return 返回给前端的data */ @ResponseStatus(code = HttpStatus.BAD_REQUEST) @ResponseBody @ExceptionHandler(value = {BindException.class, ValidationException.class, MethodArgumentNotValidException.class}) public ResultMap handleParameterVerificationException(Exception e) { String msg = null; if (e instanceof MethodArgumentNotValidException) { BindingResult bindingResult = ((MethodArgumentNotValidException) e).getBindingResult(); FieldError fieldError = bindingResult.getFieldError(); if (fieldError != null) { msg = fieldError.getDefaultMessage(); } } else if (e instanceof BindException) { FieldError fieldError = ((BindException) e).getFieldError(); if (fieldError != null) { msg = fieldError.getDefaultMessage(); } } else if (e instanceof ConstraintViolationException) { /* * ConstraintViolationException的e.getMessage()形如 * {方法名}.{参数名}: {message} * 这里只需要取后面的message即可 */ msg = e.getMessage(); if (msg != null) { int lastIndex = msg.lastIndexOf(':'); if (lastIndex >= 0) { msg = msg.substring(lastIndex + 1).trim(); } } } else { msg = "处理参数时异常"; } return ResultMap.error(ExceptionEnum.PARAMS_ERROR.getResultCode(),msg); } }

4.异常返回示例

{ "success": false, "msg": "ID不能为空", "data": null, "code": "10001" }

5.规则注解示例


限制


说明

@Null

限制只能为null

@NotNull

限制必须不为null

@AssertFalse

限制必须为false

@AssertTrue

限制必须为true

@DecimalMax(value)

限制必须为一个不大于指定值的数字

SpringBoot参数校验和自定义异常如何实现?

@DecimalMin(value)

限制必须为一个不小于指定值的数字

@Digits(integer,fraction)

限制必须为一个小数,且整数部分的位数不能超过integer,小数部分的位数不能超过fraction

@Future

限制必须是一个将来的日期

@Max(value)

限制必须为一个不大于指定值的数字

@Min(value)

限制必须为一个不小于指定值的数字

@Past

限制必须是一个过去的日期

@Pattern(value)

限制必须符合指定的正则表达式

@Size(max,min)

限制字符长度必须在min到max之间

@Past

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

@NotEmpty

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

@NotBlank

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

@Email

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