Two @GetMapping with same URL but different parameters

Viewed 1175

I'm learning Spring MVC and while in process I came across this problem:

    // http://localhost:8080/todo-list/welcomeWithParam?user=Stefan
    @GetMapping("welcomeWithParam")
    public String welcome91(@RequestParam String user, Model model) {
        model.addAttribute("helloThroughParam", demoService.getHelloMessage(user));
        return "welcome-with-model";
    }

    // http://localhost:8080/todo-list/welcomeWithParam?user=Stefan&age=31
    @GetMapping("welcomeWithParam")
    public String welcome92(@RequestParam String user, @RequestParam int age, Model model) {
        model.addAttribute("helloThroughParam", demoService.getHelloMessage(user));
        model.addAttribute("age", age);
        return "welcome-with-model";
    }

I'm getting this error:

Caused by: java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'demoController' method academy.learnprogramming.controller.DemoController#welcome92(String, int, Model) to {GET [/welcomeWithParam]}: There is already 'demoController' bean method academy.learnprogramming.controller.DemoController#welcome91(String, Model) mapped.

So, Spring is telling me we cant have two GET mappings with same URL but different number/type of parameters?

If I change value of one of @GetMapping("") values, it works fine.

1 Answers

Something like this:

@RequestMapping(value = "/welcomeWithParam", params = "user")
public String welcome91(@RequestParam String user, Model model) {
  // ...
}

@RequestMapping(value = "/welcomeWithParam", params = {"user","age"})
public ModelAndView welcome92(@RequestParam String user, @RequestParam int age, Model model) {
  // ...
}
Related