【问题标题】:@Valid does not work when @RequestPart is used in Spring在 Spring 中使用 @RequestPart 时 @Valid 不起作用
【发布时间】:2018-11-06 11:30:16
【问题描述】:

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

【问题讨论】:

  • 您正在覆盖验证器并将其绑定到模型属性。从@InitBinder 中删除"campaignCreatorDTO",然后重试。如果失败(因为您随后设置了全局验证器)尝试使用参数名称 json 而不是模型参数名称。

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


【解决方案1】:

详细here@InitBinder 使用传递给它的值进行有针对性的验证,具有相同的命名请求参数或模型属性。问题是您两者都没有,因为您在特定端点/creator 中使用了多部分表单数据输入。因此,从@InitBinder 中删除命名限制将是解决方案。

@InitBinder
public void initCreatorDTOBinder(WebDataBinder binder) { ... }

【讨论】:

    【解决方案2】:

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

    【讨论】:

    猜你喜欢
    • 2017-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-16
    • 1970-01-01
    • 2013-06-18
    • 2020-10-04
    相关资源
    最近更新 更多