将 2 个控制器方法映射到具有不同查询参数的同一端点
Map 2 controller methods to the same endpoint with different query parameters
我想在 Java 中实现一个 REST API,其端点 "overloaded" 因传递的查询参数而异。
我在我的控制器中试过这段代码 class:
@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;
}
此returns以下错误:
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 个不同方法?这可能吗?
谢谢。
您收到错误消息是因为两个端点具有相同的路径,这会混淆编译器将 API 映射到相应的路径。传递查询参数并不意味着端点具有不同的路径。您可以将这 2 个端点合二为一:
@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
。然后您可以相应地分开您的案件。
Micronaut 在匹配路由时不考虑查询参数,因此通过查询参数分隔路由是行不通的。我建议按照@Rahul 的建议去做。
我想在 Java 中实现一个 REST API,其端点 "overloaded" 因传递的查询参数而异。
我在我的控制器中试过这段代码 class:
@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;
}
此returns以下错误:
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 个不同方法?这可能吗?
谢谢。
您收到错误消息是因为两个端点具有相同的路径,这会混淆编译器将 API 映射到相应的路径。传递查询参数并不意味着端点具有不同的路径。您可以将这 2 个端点合二为一:
@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
。然后您可以相应地分开您的案件。
Micronaut 在匹配路由时不考虑查询参数,因此通过查询参数分隔路由是行不通的。我建议按照@Rahul 的建议去做。