美文网首页
Springboot Validiation Method参数校

Springboot Validiation Method参数校

作者: Airness | 来源:发表于2020-06-07 18:56 被阅读0次

    Springboot 版本 2.2.2.RELEASE
    实体校验成功,但是方法校验失败

    生效条件

    1. 方法必须是public
    2. 方法的类名上要有注解@Validated

    两个条件达成即可生效校验注解

    需要注意的是:校验失败会抛出异常ConstraintViolationException

    示例代码:

    @RestController
    @Slf4j
    @RequiresRoles(Constant.ROLE_KEY.ADMIN)
    @RequestMapping("api/v1/sys/plan")
    //标记类名
    @Validated
    public class PlanController  extends BaseController {
    
    
        @GetMapping("/{planKey}/enable")
        @Transactional
        public JsonResult<PlanEntity> setPlanEnable(
                @PathVariable String planKey,
                @EnumValid(value = Constant.STATUS.class,message = "枚举不正确") Integer enableStatus){
            return succeed(planService.setPlanEnable(planKey,enableStatus));
        }
    }
    
    

    声明:@EnumValid是自定义注解

    捕获异常:

    @ControllerAdvice
    @ResponseBody
    @Slf4j
    public class MyExceptionHandler {
    
    
        @ExceptionHandler(ConstraintViolationException.class)
        public JsonResult<List<String>> ConstraintViolationException(ConstraintViolationException e){
            List<String> list= CollectionUtil.newArrayList();
            for (ConstraintViolation<?> v:e.getConstraintViolations()){
                list.add(v.getMessage());
            }
            return JsonResult.error(Constant.ERROR_CODE.VALIDATOR_EXCEPTION,list);
        }
    }
    

    相关文章

      网友评论

          本文标题:Springboot Validiation Method参数校

          本文链接:https://www.haomeiwen.com/subject/tvxhtktx.html