java - 将 2 个控制器方法映射到具有不同查询参数的同一端点
问题描述
我想在 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 个不同方法?这可能吗?
谢谢。
解决方案
您收到错误是因为两个端点具有相同的路径,并且它混淆了编译器以将 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
。然后,您可以相应地分开您的案例。
推荐阅读
- mysql - 将工程转发到 phpmyadmin 时出现 MySQL 工作台错误
- microsoft-edge - 如何从 WSL2 启动 Edge?
- html - 带有文本的自定义复选框
- javascript - 可以在 react.js 中使用所有 HTML 片段吗?
- batch-file - 将反斜杠更改为双反斜杠
- kubernetes - Kubespray 如何在 k8s 主节点上配置 /etc/kubernetes/manifests/kube-apiserver.yaml 文件
- javascript - javascript python 3 jsonResponse 未定义
- reactjs - 在 react hooks 中生成新的组件类型,如何保持性能?
- php - WooCommerce 添加到购物车,从自定义选择字段中添加第二个产品
- java - 如何在 Java 中更改 JMenu 的字体大小?