spring mvc @RequestPart validation via annotation

冷暖自知 提交于 2020-06-26 19:44:01

问题


How can I validate that the body request part is not empty?

@PostMapping("/messages")
@ResponseStatus(HttpStatus.CREATED)
fun createMessage(@Valid @RequestPart message: MessageCreate,
                  @Valid @RequestPart @NotEmpty body: MultipartFile,
                  @RequestParam attachments: List<MultipartFile>) {
    return service.create(message, body, attachments)
}

I tried to create a custom validator annotation that checks body.isEmpty() result but it has no effect. What is missing ? Is it possible do to it this way ?


回答1:


Add @NotNull before the request body object.

Refer this for more info : Null request body not getting caught by Spring @RequestBody @Valid annotations




回答2:


@PostMapping("/messages")
@ResponseStatus(HttpStatus.CREATED)
fun createMessage(@Valid @RequestPart message: MessageCreate,
                  @Valid @RequestPart @NotEmpty body: MultipartFile,
                  result: BindingResult,
                  @RequestParam attachments: List<MultipartFile>) {

    if (result.hasErrors()) {
        //handle validation failure
    }

    return service.create(message, body, attachments)
}

Note: BindingResult argument must be declared immediately after the validated method argument.



来源:https://stackoverflow.com/questions/51763877/spring-mvc-requestpart-validation-via-annotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!