如下是我写的一段代码,其中会发现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是用来定义最大长度的

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐