问题
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