使用不同的查询参数将2种控制器方法映射到同一端点

时间:2019-10-30 12:58:47

标签: java micronaut

我想在Java中使用“过载”端点实现REST API,该端点因传递的查询参数而有所不同。
我已经在控制器类中尝试了以下代码:

@Get("/query")
public MyResponse queryByDate(@QueryValue @Valid @Format("yyyy-MM-dd") Date date) {
    // Code to generate the response
    return retval;
}

@Get("/query")
public MyResponse queryByDateAndValue(@QueryValue @Valid @Format("yyyy-MM-dd") Date date, @QueryValue int value) {
    // Code to generate the response
    return retval;
}

这将返回以下错误:

More than 1 route matched the incoming request. The following routes matched /calendar/years/query: GET - /calendar/years/query, GET - /calendar/years/query
io.micronaut.web.router.exceptions.DuplicateRouteException: More than 1 route matched the incoming request. The following routes matched /calendar/years/query: GET - /calendar/years/query, GET - /calendar/years/query

请注意,如果我删除其中一种方法,其余方法将按预期工作。 如何将具有不同查询参数的端点映射到控制器中的2种不同方法?这可能吗?

谢谢。

2 个答案:

答案 0 :(得分:0)

由于两个端点具有相同的路径,并且使编译器无法将API映射到相应的路径,因此您会收到错误消息。传递查询参数并不意味着端点具有不同的路径。您可以将这两个端点组合成一个端点:

@Get("/query")
public MyResponse queryByDateAndValue(@QueryValue @Valid @Format("yyyy-MM-dd") Date date,@DefaultValue("1")  @QueryValue int value) {
    // Code to generate the response
    return retval;
}

,并设置默认值value。然后,您可以相应地分离案件。

答案 1 :(得分:0)

Micronaut在匹配路线时不考虑查询参数,因此按查询参数分隔路线将永远无效。我建议做@Rahul建议的事情。