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.
We can use a name such as a redirect: http://localhost:8080/spring-redirect-and-forward/redirectedUrl if we need to redirect to an absolute URL.
A request can be basically processed in three ways: a) resolved by Spring in a controller action, b) forwarded to a different controller action, c) redirected to client to fetch another URL. Forward: performed internally by Spring. the browser is completely unaware of forward, so its original URL remains intact.
You can use RedirectAttributes to store flash attributes and they will be automatically propagated to the "output" FlashMap of the current request. A RedirectAttributes model is empty when the method is called and is never used unless the method returns a redirect view name or a RedirectView.
Try a URL http://localhost:8080/HelloWeb/index and you should see the following result if everything is fine with your Spring Web Application. Click the "Redirect Page" button to submit the form and to get the final redirected page.
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"; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With