Anthony
Anthony

Reputation: 917

Spring 3.0 forwarding request to different controller

What is the proper way to forward a request in spring to a different controller?

@RequestMapping({"/someurl"})
public ModelAndView execute(Model model) {
    if (someCondition) {
        //forward to controller A
    } else {
        //forward to controller B
    }
}

All of the controller have dependencies injected by Spring, so I can't just create them and call them myself, but I want the request attributes to be passed on to the other controllers.

Upvotes: 28

Views: 45829

Answers (3)

Eugene Kuleshov
Eugene Kuleshov

Reputation: 31795

You can use view name like "redirect:controllerName" or "forward:controllerName". The latter will reroute request to another controller and former will tell browser to redirect request to another url.

docs: https://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#mvc-redirecting-redirect-prefix

Upvotes: 6

Krishna Kumar Chourasiya
Krishna Kumar Chourasiya

Reputation: 2136

You can use Spring RedirectView to dispatch request from one controller to other controller. It will be by default Request type "GET"

RedirectView redirectView = new RedirectView("/controllerRequestMapping/methodmapping.do", true);

Upvotes: 1

John Vint
John Vint

Reputation: 40256

Try returning a String instead, and the String being the forward url.

@RequestMapping({"/someurl"})
public String execute(Model model) {
    if (someCondition) {
        return "forward:/someUrlA";
    } else {
        return "forward:/someUrlB";
    }
}

Upvotes: 38

Related Questions