在Spring中使用@RequestPart时,@ Valid不起作用

时间:2018-11-06 11:30:16

标签: java spring spring-mvc spring-boot spring-validator

使用@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) {
}

2 个答案:

答案 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);
}