[英]How to force a bean request parameter to be required in Spring Rest MVC?
I'm using Spring 5 for a REST API and I can't get how to mark request parameters required so that Spring would reply 400 Bad request
instead of letting the request reach the controller method. 我使用的是REST API的Spring 5,但我无法获得如何标记要求的请求参数的方法,因此Spring会回复
400 Bad request
而不是让请求到达控制器方法。
My methods use a bean to receive query string parameters, so @RequestParam(required=true)
is not an option here: 我的方法使用bean来接收查询字符串参数,因此
@RequestParam(required=true)
在这里不是一个选择:
@GetMapping(path="")
public String findAll(Filter filter) {
// ...
}
A Filter
looks like this: Filter
如下所示:
public class Filter {
private String id;
private String usersId;
private GregorianCalendar dayStart;
private GregorianCalendar dayEnd;
// ...
}
I'd like to require ie just usersId
to be mandatory. 我想只要求
usersId
是强制性的。
Is there anything like that or should I manually validate the input? 有没有类似的事情,还是我应该手动验证输入?
You could use something like this 你可以用这样的东西
@GetMapping(path="")
public String findAll(@Valid Filter filter) {
// ...
}
And on your Filter
class 在您的
Filter
类上
public class Filter {
private String id;
@NotNull
private String usersId;
private GregorianCalendar dayStart;
private GregorianCalendar dayEnd;
// ...
}
You should also make sure that 您还应确保
You can user javax.validation.Valid
to validate your bean and instead of using @GetMapping
you can use @PostMapping
. 您可以使用
javax.validation.Valid
来验证您的bean,而不是使用@GetMapping
,而可以使用@PostMapping
。
@PostMapping(path="")
public String findAll(@Valid Filter filter) {
// ...
}
and in your Filter
class you can use @NotNull
of javax.validation.constraints.NotNull
and @NotEmpty
of javax.validation.constraints.NotEmpty
并在
Filter
类,你可以使用@NotNull
的javax.validation.constraints.NotNull
和@NotEmpty
的javax.validation.constraints.NotEmpty
public class Filter {
private String id;
@NotNull
@NotEmpty
private String usersId;
private GregorianCalendar dayStart;
private GregorianCalendar dayEnd;
// ...
}
For more detail for validation look at here 有关验证的更多详细信息,请参见此处
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.