I want to add @NotEmpty
in @RequestBody
, but i don't want to create additional POJO just for the request, how can i do that?
I want to do like the following, but it still return me 201 Created
status code when i put []
in request body, it means that @NotEmpty
is actually not working.
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public void create(@Valid @NotEmpty @RequestBody Set<String> request) {
.....
}
I DO NOT WANT to do something like this, but the @NotEmpty
works in this case :
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public void create(@Valid @NotEmpty @RequestBody SampleRequest request) {
.....
}
SampleRequest class
public class SampleRequest {
@NotEmpty
private Set<String> name;
..Setter and Getter
}
您还需要使用@Validated ( https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/validation/annotation/Validated.html ) 注释您的控制器、方法或参数,以便触发验证
Add annotation @Validated
on controller class and then validation will be work for method parameters. For details, you can look at tutorial here https://www.baeldung.com/spring-validate-list-controller .
First thing I would do is check that there's a validation implementation on your classpath. The @NotEmpty annotation comes from a separate jar ( validation-api.jar
), so it's possible that, while your code compiles, validation is not being enforced at runtime. You should see a dependency named something like hibernate-validator.jar
Failing that, you could try replacing it with @Size(min=1)
As you're not validating complex Java objects like DTOs, so you can put constraint (validation annotations) on your method parameters.
You only need to do two things
1-put constraint (valiadtion) annotation before the method parameter
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public void create(@RequestBody @NotEmpty SampleRequest request) {
.....
}
2-Put @Validated on the class
@Validated
public class testController{
//..
}
Finally, we have
@Validated
public class testController{
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public void create(@RequestBody @NotEmpty SampleRequest request) {
//..
}
}
Some helpful link
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.