[英]Make Spring java object request parameter required
I have the following controller code 我有以下控制器代码
@GetMapping("/users")
public ResponseEntity<UserDto> getUsers(Filter filter) {
return ResponseEntity.ok(userService.findUsers(filter));
}
Filter.java: Filter.java:
public class Filter {
private Integer page;
private Integer size;
private String sort;
... lots of other parameters
}
The request parameters are written as a Java object to avoid adding lots of parameters to controller. 请求参数被写为Java对象,以避免向控制器添加大量参数。 However, all of the parameters are made optional by Spring.
但是,所有参数都是Spring可选的。 What I want is to have some parameters like
page
and size
required, but others like sort
optional. 我想要的是有一些参数,如
page
和size
需要,但其他像sort
可选。 If I had them as controller parameters, I could use @RequestParam(required = true/false)
. 如果我将它们作为控制器参数,我可以使用
@RequestParam(required = true/false)
。 Is it possible to do something similar in Java class? 是否有可能在Java类中做类似的事情?
You can use the javax.validation API to specify some constraints on the fields of a class. 您可以使用javax.validation API为类的字段指定一些约束。
In your case you could use @NotNull
and @NotEmpty
according to your requirements and the field types such as : 在您的情况下,您可以根据您的要求和字段类型使用
@NotNull
和@NotEmpty
,例如:
import javax.validation.constraints.NotNull;
import javax.validation.constraints.NotEmpty;
...
public class Filter {
@NotNull
private Integer page;
@NotEmpty
private Integer size;
private String sort;
... lots of other parameters
}
Then specify the @Valid
annotation for the parameter you want to validate : 然后为要验证的参数指定
@Valid
注释:
import javax.validation.Valid;
...
@GetMapping("/users")
public ResponseEntity<UserDto> getUsers(@Valid Filter filter) {
return ResponseEntity.ok(userService.findUsers(filter));
}
If the filter parameter doesn't respect the constraints, a ConstraintViolationException
is thrown that you can leave or catch to map it to a specific client 4XX error by using a Spring exception handler such as @ControllerAdvice
. 如果filter参数不遵守约束,则抛出
ConstraintViolationException
,您可以通过使用Spring异常处理程序(如@ControllerAdvice
将其保留或捕获以将其映射到特定客户端4XX错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.