sublime
sublime

Reputation: 4161

Handle same URL in different controllers based on parameters - Spring MVC

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?

Upvotes: 3

Views: 3836

Answers (2)

Si mo
Si mo

Reputation: 979

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

Upvotes: 10

lynnsea
lynnsea

Reputation: 137

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

Upvotes: -4

Related Questions