Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

spring - Accessing multiple controllers with same request mapping

Please find my HomeController and DemoController

class HomeController{
@RequestMapping(value="index")
public void home(){
}
}

class DemoController{
@RequestMapping(value="index")
public void demo(){
}
}

when I try to send a request to index, which one will get executed? I wanted to know how can we have same request mapping value for multiple controllers

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

https://stackoverflow.com/a/34590355/2682499 is only partially correct at this point.

You can have multiple controller methods use the same URI so long as you provide Spring enough additional information on which one it should use. Whether or not you should do this is a different question. I would certainly not recommend using the same URI in two separate controller classes to avoid confusion, though.

You can do something like this:

class HomeController{
    @RequestMapping(value="/index", params = {"!name", "!foo"})
    public List<Something> listItems(){
        // retrieve Something list
    }

    @RequestMapping(value="/index", params = "name")
    public List<Something> listItems(String name) {
        // retrieve Something list WHERE name LIKE %name%
    }

    @RequestMapping(value="/index", params = {"!name", "foo"})
    public List<Something> listItems(String foo) {
        // Do something completely different
    }
}

For the full documentation on what is possible when overloading URIs you should reference the @ReqeustMapping documentation: https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html. And, specifically https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html#params-- for the section request parameters.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...