【问题标题】:Two @GetMapping with same URL but different parameters两个具有相同 URL 但参数不同的 @GetMapping
【发布时间】:2021-09-02 07:53:02
【问题描述】:

我正在学习 Spring MVC,在学习过程中我遇到了这个问题:

    // 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";
    }

我收到此错误:

原因:java.lang.IllegalStateException:不明确的映射。无法映射“demoController”方法 academy.learnprogramming.controller.DemoController#welcome92(字符串,整数,模型) 到 {GET [/welcomeWithParam]}:已经有 'demoController' bean 方法 academy.learnprogramming.controller.DemoController#welcome91(String, Model) 映射。

那么,Spring 告诉我我们不能有两个具有相同 URL 但参数数量/类型不同的 GET 映射?

如果我更改 @GetMapping("") 值之一的值,它可以正常工作。

【问题讨论】:

  • 你可以在@GetMapping注解中使用params="user" 和params = {"user","age"}。
  • @lutfucan 非常感谢,我最喜欢你的回答。

标签: spring model-view-controller parameters get controller


【解决方案1】:

类似这样的:

@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) {
  // ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多