SpringBoot中的注释使用(@Valid,@Size,@NotNull,@Max)
@Valid,@Size,@NotNull,@Max的简单使用
·
如下是我写的一段代码,其中会发现if中的条件判断过于繁琐,如果需要更多的属性判断,那代码量难以估量
@PostMapping("/admin/category/add")
@ResponseBody
public APIRestResponse addCategory(HttpSession session, @RequestBody AddCategoryReq addCategoryReq){
//名字,类型等属性不能为空
if(addCategoryReq.getCategoryName()==null
|| addCategoryReq.getCategoryType()==null
|| addCategoryReq.getCategoryOrderNum()==null
|| addCategoryReq.getCategoryParentId()==null)
{
return APIRestResponse.error(CarExceptionEnum.NAME_NOT_NULL);
}
User currentUser=(User)session.getAttribute(Constant.CAR_MALL_USER);
if(currentUser==null){
return APIRestResponse.error(CarExceptionEnum.NEED_LOGIN);
}
//校验是否为管理员
boolean adminRole = userService.checkAdminRole(currentUser);
if(adminRole){
//是管理员执行操作
categoryService.add(addCategoryReq);
return APIRestResponse.success();
}
else {
return APIRestResponse.error(CarExceptionEnum.NEED_ADMIN);
}
}
这里说一下@Valid,@Size,@NotNull,@Max对于以上问题的解决方法
@Valid注解无效可以参考以下链接
@Valid无效怎么办
回归正题,现在我们将@RequestBody AddCategoryReq addCategoryReq
前加入@Valid字段,(@Valid 注解通常用于对象属性字段的规则检测)
删除第一个if语句:
@PostMapping("/admin/category/add")
@ResponseBody
public APIRestResponse addCategory(HttpSession session,@Valid @RequestBody AddCategoryReq addCategoryReq){
User currentUser=(User)session.getAttribute(Constant.CAR_MALL_USER);
if(currentUser==null){
return APIRestResponse.error(CarExceptionEnum.NEED_LOGIN);
}
//校验是否为管理员
boolean adminRole = userService.checkAdminRole(currentUser);
if(adminRole){
//是管理员执行操作
categoryService.add(addCategoryReq);
return APIRestResponse.success();
}
else {
return APIRestResponse.error(CarExceptionEnum.NEED_ADMIN);
}
}
}
在AddCategoryReq的类中加上@Size,@NotNull,@Max
public class AddCategoryReq {
@Size(min = 2,max = 5)
@NotNull
private String CategoryName;
@NotNull
@Max(3)
private Integer CategoryType;
@NotNull
private Integer CategoryParentId;
@NotNull
private Integer CategoryOrderNum;
}
这里我的set,get方法省略不写。@NotNull为不可为空,@Size是用来限制字段的长度大小,其中需要两个参数,一个是min,用来定义最小长度,max用来定义最大长度,@Max是用来定义最大长度的。
更多推荐
已为社区贡献1条内容
所有评论(0)