如何验证@pathvariable是否已设置?

ibps3vxo  于 2021-07-05  发布在  Java
关注(0)|答案(3)|浏览(362)

这是我的 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) {

但当我调用 /stats/2020-05-30/ 其中不包括 toDate 我收到的答复是:

{
    "timestamp": "2020-09-04T06:02:46.567+00:00",
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/stats/2020-05-30/"
}

所以注解没有正确注册?
更新:
似乎pathvariable不是要验证的:
验证器(@validated@valid)不适用于spring和tomee

m1m5dgzv

m1m5dgzv1#

将以下注解添加到为我工作的类中(而不是方法)

@Validated
ac1kyiln

ac1kyiln2#

实际上,spring通过发送404向客户机返回正确答案。当有人没有提供完整的url时,404是响应的状态。
正确的验证方法是使用date、localdate或类似的日期类来代替string。可能您需要定义正确的日期格式,因此请查看以下链接以了解详细信息。https://www.baeldung.com/spring-date-parameters

wmvff8tz

wmvff8tz3#

在rest中,路径变量是资源url的一部分。因此,如果路径/url的一部分丢失,则资源是不同的。
这就是为什么404是正确的响应代码。
如果这两个变量可以为空,那么它们应该是@requestparam。

相关问题