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?

1
  • This question has a similar approach. Commented Nov 16, 2015 at 8:09

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.