首页 > 解决方案 > 在 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查询参数时才响应。对于其他任何事情,即使它是两个参数的组合,我也希望它忽略。

为什么它会在这里抛出模棱两可的错误,我们该如何处理?

标签: javaspringspring-bootrestspring-restcontroller

解决方案


您可以使用@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);
    }

推荐阅读