@RequestMapping(value = /test,method = RequestMethod.POST)
public void test(@RequestBody @Valid SyncProductInfoForm syncProductInfoForm,
BindingResult bindingResult)//將校驗結果放到BindingResult對象中 {
logger.info("syncProductinfo param={}",syncProductInfoForm);
if(bindingResult.hasErrors()) {
ObjectError objectError = bindingResult.getAllErrors().get(0);
Response.buildResponseWithMsg(result, ResponseEnum.PARAM_ERROR.getCode(), objectError.getDefaultMessage());
return result;
}
}
import lombok.Data;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
@Data
public class SyncProductInfoForm {
/*cms商品id*/
@NotBlank(message = "cmsProductId不能爲空")
private String cmsProductId;
/*擴展圖片*/
@Valid
private List<ProductExtendImgForm> productExtendImgList;
/*sku信息*/
@Valid //用來遞歸校驗-多層校驗
@NotEmpty(message = "productSkuInfoList不能爲空")
private List<ProductSkuInfoForm> productSkuInfoList;
}
@Data
public class ProductExtendImgForm {
/*圖片地址*/
@NotBlank(message = "productImgUrl不能爲空")
private String productImgUrl;
/*圖片權重*/
private String productImgWeight;
}
複製代碼
校驗方式二:html
public static void main(String[] args) {
PostBackBindCarInfoForm postBackBindCarInfoForm = new PostBackBindCarInfoForm();
postBackBindCarInfoForm.setCarNo("");
ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
Validator validator = vf.getValidator();
Set<ConstraintViolation<PostBackBindCarInfoForm>> set = validator.validate(postBackBindCarInfoForm);
set.stream().forEach(item->{
System.out.println(item.getMessage());
});
}
複製代碼
參考:www.cnblogs.com/cjsblog/p/8…java