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 contro开发者_如何学编程ller 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.
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";
}
}
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
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);
精彩评论