英文:
How to validate @PathVariable is set?
问题
以下是翻译好的内容:
这是我的Get
请求:
@GetMapping("/stats/{fromDate}/{toDate}")
public StatsSummary getStatsSummary(@PathVariable String fromDate, @PathVariable String toDate) {
logger.info("Calculating statistics between" + fromDate + ",to" + toDate);
return statsService.getStatsSummary(fromDate, toDate);
}
我尝试将注解@NotBlank
添加为:
public StatsSummary getStatsSummary(@PathVariable String fromDate, @PathVariable @NotBlank String toDate) {
但是,当我调用不包括toDate
的/stats/2020-05-30/
时,我收到以下响应:
{
"timestamp": "2020-09-04T06:02:46.567+00:00",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/stats/2020-05-30/"
}
所以注解没有被正确地注册?
更新:
似乎PathVariable
不打算进行验证:
英文:
Here is my Get
request:
@GetMapping("/stats/{fromDate}/{toDate}")
public StatsSummary getStatsSummary(@PathVariable String fromDate, @PathVariable String toDate) {
logger.info("Calculating statistics between" + fromDate + ",to" + toDate);
return statsService.getStatsSummary(fromDate, toDate);
}
I've tried adding the annotation @NotBlank
as:
public StatsSummary getStatsSummary(@PathVariable String fromDate, @PathVariable @NotBlank String toDate) {
but when I invoke /stats/2020-05-30/
which does not include toDate
I receive the response:
{
"timestamp": "2020-09-04T06:02:46.567+00:00",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/stats/2020-05-30/"
}
So the annotation is not being registered correctly?
Update:
It seems PathVariable is not meant to be validated:
答案1
得分: 2
在REST中,路径变量是资源URL的一部分。因此,如果路径/URL的某个部分丢失,资源就会不同。
这就是为什么404是正确的响应代码。
如果这两个变量可以为空,它们应该使用@RequestParam。
英文:
In REST, path variables are part of the resource URL. Therefore, if a part of the path/URL is missing, the resource is different.
That is why a 404 is the correct response code.
If those two variables can be empty, they should be @RequestParam.
答案2
得分: 1
实际上,Spring通过发送404状态码向客户端返回了正确的响应。
当有人没有提供完整的URL时,404状态码是要响应的状态码。
正确的验证方式是使用一些日期类,如Date或LocalDate,而不是String。
可能你需要定义日期的适当格式,所以可以查看下面的链接了解详情。
https://www.baeldung.com/spring-date-parameters
英文:
Actually Spring by sending 404 returns correct answer to a client.
When someone doesn't provide full URL, the 404 is the status to respond.
The proper way to validate that is to use some date class like Date or LocalDate or similar instead of String.
Probably you'll need to define proper formatting of date so take a look at the following link for details.
https://www.baeldung.com/spring-date-parameters
答案3
得分: 0
将以下注解添加到适合我的类中(不是方法)
@Validated
英文:
Add the following annotation to the class worked for me.(Not to the method)
@Validated
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论