Spring MVC - Request mapping, two urls with two different parameters

前端 未结 3 2079
傲寒
傲寒 2020-12-17 22:22

Is it possible in Spring to have one method with two different urls with different params for each method?

Below is pseudo code

@RequestMethod(URL1-p         


        
相关标签:
3条回答
  • 2020-12-17 22:41

    you can supply multiple mappings for your handler like this

    @RequestMapping(value={"", "/", "welcome"})
    public void handleAction(@ModelAttribute("A") A a, ...) { }
    

    But if you want to use different parameters for each mapping, then you have to extract your method.

    0 讨论(0)
  • 2020-12-17 22:42

    Something like this

    @RequestMapping(value={"URL1"}, method=RequestMethod.POST)
    public String handleSubmit(@ModelAttribute("A") A command, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        return helperSubmit();
    }
    
    @RequestMapping(value={"URL2"}, method=RequestMethod.POST)
    public String handleSubmit(@ModelAttribute("A") A command, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        return helperSubmit();
    }
    
    private helperSubmit() {
      return "redirect:" + someUrl;
    }
    
    0 讨论(0)
  • 2020-12-17 22:48

    Update: It appears your question is completely different.

    No, you can't have the same url with different parameters in different controllers. And it doesn't make much sense - the url specifies a resource or action, and it cannot be named exactly the same way in two controllers (which denote different behaviours).

    You have two options:

    • use different URLs
    • use one method in a misc controller that dispatches to the different controllers (which are injected) depending on the request param.

    Original answer:

    No. But you can have two methods that do the same thing:

    @RequestMethod("/foo")
    public void foo(@ModelAttribute("A") A a) {
        foobar(a, null);
    }
    
    @RequestMethod("/bar")
    public void bar(@ModelAttribute("B") B b) {
        foobar(null, b);
    }
    

    If I haven't understood correctly, and you want the same ModelAttribute, then simply:

    @RequestMapping(value={"/foo", "/bar"})
    

    And finally - if you need different request parameters, you can use @RequestParam(required=false) to list all possible params.

    0 讨论(0)
提交回复
热议问题