当controller方法入参是简单参数时使用Validated进行校验

本文主要针对controller层中,对于单个参数的校验:

1、引入依赖

org.hibernate hibernate-validator 5.3.1.Final 2、首先,需要我们声明一个Bean,注入校验器到Spring Boot的运行环境,负责不能生效对应的@Range、@Min、@Max等validator包里面提供的注解

@Configuration
@EnableAutoConfiguration
public class ValidatorConfig {
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor(){
return new MethodValidationPostProcessor();
}
}
3、controller层

特别注意:

1、@Validated要在controller上标注

@Api(value = “type”, description = “辅导类型”)
@RestController
@Validated
@RequestMapping(value = “type”)
public class CompositionTypesController extends BaseController {
@ApiOperation(value=“新增辅导类型”, notes=“新增辅导类型”)
@LoginRequired
@PostMapping(value = “addCompostionTyp1e”)
public Response addCompostionTyp1e(@ApiParam(value = “成绩”) @Max(value = 60,message = “得分必须小于60”) @RequestParam int score, @ApiParam(value = “年龄”) @Min(value = 3, message = “年龄大于3岁”) @RequestParam int age, @ApiParam(value = “辅导作文类型”) @NotNull(message = “辅导作文类型不能为空”) @RequestParam(required = false) String name){
//校验
logger.info(String.valueOf(age));
return success(ResponseCode.OK);
}
}

4、统一异常捕获

@ControllerAdvice
public class ExceptionAdvice {
/**
* 拦截捕捉自定义异常 ConstraintViolationException.class
* @param ex
* @return
*/
@ResponseBody
@ExceptionHandler(value = ConstraintViolationException.class)
public Map ConstraintViolationExceptionHandler(ConstraintViolationException ex) {
Map map = new HashMap();
Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
Iterator<ConstraintViolation<?>> iterator = constraintViolations.iterator();
List msgList = new ArrayList<>();
while (iterator.hasNext()) {
ConstraintViolation<?> cvl = iterator.next();
msgList.add(cvl.getMessageTemplate());
}
map.put(“status”, ExceptionCode.CVL_EXCEPTION);
map.put(“msg”, msgList);
return map;
}
}

5、在swagger中进行接口调试

注:

校验常用的注解如下:

@AssertFalse 校验false
@AssertTrue 校验true
@DecimalMax(value=,inclusive=) 小于等于value,
inclusive=true,是小于等于
@DecimalMin(value=,inclusive=) 与上类似
@Max(value=) 小于等于value
@Min(value=) 大于等于value
@NotNull 检查Null
@Past 检查日期
@Pattern(regex=,flag=) 正则
@Size(min=, max=) 字符串,集合,map限制大小
@Valid 对po实体类进行校验
@NotNull 和 @NotEmpty 和@NotBlank 区别

@NotEmpty 用在集合类上面

@NotBlank 用在String上面

@NotNull 用在基本类型上

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值