3

I have a controller which handles a specific URL

@RequestMapping(value= {"/myurl"})
public ModelAndView handleMyURL()

Instead I want to have 2 separate controllers that let me handle this same /myurl based on the parameters passed to it.

If URL is

/myurl?a=1 

goto controller A, otherwise use controller B. Is there a way to do that?

I found this similar question Spring MVC - Request mapping, two urls with two different parameters where someone has mentioned "use one method in a misc controller that dispatches to the different controllers (which are injected) depending on the request param." , how do I implement that?

Community
  • 1
  • 1
sublime
  • 4,013
  • 9
  • 53
  • 92
  • [This](http://stackoverflow.com/questions/9208210/how-to-split-spring-mvc-request-mapping-by-parameter-value?rq=1) question has a similar approach. – nmy Nov 16 '15 at 08:09

2 Answers2

10

Controller 1

@RequestMapping(value= {"/myurl"}, params = { "a" })
public ModelAndView handleMyURL()

Controller 2

@RequestMapping(value= {"/myurl"}, params = { "b" })
public ModelAndView handleMyURL()

Take a look at chapter 4 of this post for more detail

Glenn Van Schil
  • 1,059
  • 3
  • 15
  • 33
Si mo
  • 969
  • 9
  • 24
-4
@Controller
@RequestMapping(value= {"/myurl"})
public TestController{
    @Autoware 
    private TestAController testAController;
    @Autoware 
    private TestBController testBController;

    public void myMethod(String a){
        if(a.equals("1"){
            testAController.foo(a);
        }else{
            testBController.foo(a);
        }

    }
}

@Controller
@RequestMapping(value= {"/myurl1"})
public class TestAController{
   public void foo(String a){
    ...
}
}

@Controller
@RequestMapping(value= {"/myurl2"})
public class TestBController{
    public void foo(String a){
     ...
    }
}
lynnsea
  • 137
  • 1
  • 9
  • Sorry to downvote, but I don't like this. If you don't want to use two separate controllers (it is possible, see other answer) and want one controller to "control" the behavior of the url, I suggest 1) split the business services and keep one controller, or 2) if really want 2 controllers managed by one controller (maybe you have a lot of parameters to handle, or whatever) just redirect to other controller; do not call directly a controller method. – cripox May 09 '17 at 04:10