@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;
}
复制代码
校验方式二:
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());
});
}
复制代码