SpringBoot表單校驗之@NotNull、@NotEmpty、@NotBlank的區別

保存或者修改進行表單提交時,一般後端對前端返回數據進行約定校驗,其中最常用的就是非空判斷。涉及到註解@NotNull、@NotEmpty、@NotBlank

三者的區別如下:

  • @NotNull:不能爲null,但可以爲empty(""," “,” ") ,一般用在基本數據類型的非空校驗上,而且被其標註的字段可以使用 @size/@Max/@Min對字段數值進行大小的控制,例如Integer、BigDecimal、String等
  • @NotBlank: 只應用於char值可讀序列,即只用於String,且不能爲null
  • @NotEmpty:不能爲null,而且長度必須大於0(" “,” "),一般用在集合類上面
@ApiModelProperty(value = "保存")
@NotNull(groups = { ReesponseDTO.Save.class }, message = "message不能爲空")
private String message;


@ApiModelProperty(notes = "服務價格")
@NotNull(groups = { ReesponseDTO.Save.class }, message = "服務價格不能爲空")
private BigDecimal specPrice;


@ApiModelProperty(value = "姓名")
@NotBlank(groups = { ReesponseDTO.Save.class }, message = "姓名不能爲空")
private String name;


@ApiModelProperty(value = "證件材料")
@NotEmpty(groups = {ReesponseDTO.Update.class, ReesponseDTO.Save.class}, message = "證件材料不能爲空")
@Valid
private List<FileDTO> mournerFiles;

 一般會給dto加上

 public interface Save {};

 public interface Update{};

然後在collection

加上@Validated註解

 @ApiOperation(value = "提交信息接口",notes = "此接口用於提交信息")
 @RequestMapping(method = RequestMethod.POST, value = "/submit")
 public ApiResponse<ManageEntity> submit(@RequestBody @Validated({ReesponseDTO.Save.class}) ReesponseDTO reesponseDTO){

....

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章