springboot 如何校验javabean

  1. 1.springboot 如何校验javabean
    1. (1).建一个exceptionUtil工具类
    2. (2).controller类中添加注解 @Valid
    3. (3).javabean中添加三个校验注解

1.springboot 如何校验javabean

(1).建一个exceptionUtil工具类

@RestControllerAdvice
public class ExceptionHandlerUtil {

     @ResponseBody
     @ExceptionHandler(MethodArgumentNotValidException.class)
        public ReturnResultJson  exceptionHandler(MethodArgumentNotValidException e)
        {
            return new ReturnResultJson(false,"","-99",e.getBindingResult().getFieldError().getDefaultMessage());
        }
}

(2).controller类中添加注解 @Valid

@PostMapping(value= {"/saveOrUpdateAllocationHead"})
public String save(@RequestBody @Valid AnGoodsAllocationHead anGoodsAllocationHead) {
        String msg = anGoodsAllocationHeadService.saveOrUpdateGoodsAllocationHead(anGoodsAllocationHead);
        return msg;
}

(3).javabean中添加三个校验注解

@NotEmpty 用在集合类上面
@NotBlank 用在String上面
@NotNull    用在基本类型上 

public class AnGoodsAllocationHead {

    @NotBlank(message="电商企业信用代码为必填项不能为空")
    private String creditCode;

    @NotNull(message="总数量必填项不能为空")
       private Double goodsQtyTotal;

    @NotEmpty(message="list不能为空")
       private List<AnGoodsAllocationBody> list;

}

文章标题:springboot 如何校验javabean

发布时间:2021-04-21, 22:40:31

最后更新:2021-04-21, 22:36:47