java - 在 Spring 的 GetMapping 中使用参数会导致多个参数的处理程序方法不明确
问题描述
我在 Spring Boot 中有以下 REST 端点
@GetMapping(value = "students", params = {"name"})
public ResponseEntity<?> getByName(@RequestParam final String name) {
return new ResponseEntity<>(true, HttpStatus.OK);
}
@GetMapping(value = "students", params = {"tag"})
public ResponseEntity<?> getByTag(@RequestParam final String tag) {
return new ResponseEntity<>(true, HttpStatus.OK);
}
上述处理程序适用于以下请求:
localhost:8080/test/students?name="Aron"
localhost:8080/test/students?tag="player"
但是,每当我尝试以下操作时:
localhost:8060/test/students?name="Aron"&tag="player"
它抛出java.lang.IllegalStateException: Ambiguous handler methods mapped
并响应HTTP 500
我怎样才能改变这种行为?我希望我的应用程序仅在获得tag
查询参数或name
查询参数时才响应。对于其他任何事情,即使它是两个参数的组合,我也希望它忽略。
为什么它会在这里抛出模棱两可的错误,我们该如何处理?
解决方案
您可以使用@RequestParam(required = false)
:
@GetMapping(value = "students")
public ResponseEntity<?> get(
@RequestParam(required = false) final String name,
@RequestParam(required = false) final String tag) {
if ((name == null) == (tag == null)) {
return new ResponseEntity<>(false, HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(true, HttpStatus.OK);
}
推荐阅读
- c - 使用 CreateThreadpoolWork/SubmitThreadpoolWork 时向回调函数传递不同的值
- postgresql - 我的查询未显示所需结果并在未知情况下省略了值
- hyperledger-fabric - 超级账本背书政策和调用链码错误(不更新账本)
- redux - 如何使用 redux 更新/删除对象中的值
- algorithm - 用 invmap 代替 fmap 和 contramap 的推导
- javascript - 使用 iframe 时会使用什么 url?
- salesforce - Salesforce 动态操作缺少编辑按钮突出显示面板
- reactjs - 使用 React 调用模拟键盘事件和测试 stopImmediatePropagation
- azure - 如何将多个 CloudBlockBlob 对象连接到 Azure 中的一个 CloudBlockBlob 对象?
- django - 按模板中的日期过滤