@Valid
时, @RequestPart
注释未调用验证程序。在其他地方,我将@Valid
与@RequestBody
一起使用,效果很好。
只是通过错误的验证也没有错误。
下面是代码。
@InitBinder("campaignCreatorDTO")
public void initCreatorDTOBinder(WebDataBinder binder) {
binder.addValidators(new CreatorDTOValidator());
}
@PostMapping(value = "/creator", consumes = {"multipart/form-data"}, produces = {"application/json"})
@ResponseBody
@ResponseStatus(HttpStatus.CREATED)
public @Valid
ResponseDTO creator(@Valid @RequestPart("json") CampaignCreatorDTO campaignCreatorDTO,
@RequestPart(name = "file", required = false) MultipartFile adGraphic) {
}
答案 0 :(得分:1)
如here所述,@InitBinder
使用传递给它的值进行具有相同命名请求参数或模型属性的定向验证。问题是您都没有,因为您没有在特定端点/creator
中使用多部分表单数据输入。因此,从@InitBinder
中删除命名限制将是解决方案。
@InitBinder
public void initCreatorDTOBinder(WebDataBinder binder) { ... }
答案 1 :(得分:0)
使用Validator Bean在控制器方法中运行验证:
org.springframework.validation.Validator
@Autowired
protected Validator validator;
PostMapping(value = "/creator", consumes = {"multipart/form-data"}, produces = {"application/json"})
@ResponseBody
@ResponseStatus(HttpStatus.CREATED)
public @Valid
ResponseDTO creator(@RequestPart("json") CampaignCreatorDTO campaignCreatorDTO,
@RequestPart(name = "file", required = false) MultipartFile adGraphic) {
validator.validate(campaignCreatorDTO);
}