[英]Using params in GetMapping in Spring results in ambiguous handler method for multiple parameters
我在 Spring 启动中有以下 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
and respond with an 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);
}
看来您可以在参数中使用否定。 就像是:
@GetMapping(value = "students", params = {"name", "!tag"})
public ResponseEntity<?> getByName(@RequestParam final String name) {
return new ResponseEntity<>(true, HttpStatus.OK);
}
@GetMapping(value = "students", params = {"tag", "!name"})
public ResponseEntity<?> getByTag(@RequestParam final String tag) {
return new ResponseEntity<>(true, HttpStatus.OK);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.