In spring controller class to redirect to a url
some places all using return "redirect:/abc.htm";
.
also using return new ModelAndView("redirect:/abc.htm")
.
Any one please explain the difference and similarities of both statements.
And in which situation it has to use.
Rohit:
Am using RedirectAttribute to get values from old url.
In this case am getting value while using this return "redirect:/abc.htm";
but not in this return new ModelAndView("redirect:/abc.htm")
.
Is there any difference in RedirectAttributes
Forward: is faster, the client browser is not involved, the browser displays the original URL, the request is transfered do the forwarded URL. Redirect: is slower, the client browser is involved, the browser displays the redirected URL, it creates a new request to the redirected URL.
The statements:
return "redirect:/abc.htm"
return new ModelAndView("redirect:/abc.htm")
do the same thing: redirects
the request to abc.htm
. If a view name is returned that has the
prefix redirect:
, this is recognized as a special indication that a redirect is needed. The rest of the view name will be treated as the redirect URL.
With the statement
return "redirect:/abc.htm"
you can only return the redirect view name.
With ModelAndView
you can return both model
and view
in a single return value:
ModelAndView modelAndView = new ModelAndView("redirect:/abc.htm");
modelAndView.addObject("modelAttribute" , new ModelAttribute());
return modelAndView;
But the attribute value will not be available in the new redirect request that the client(browser) will make for the URL /abc.htm
. The best use of ModelAndView
is when you forward the request to a new URL, so that you can return both model
and view
together in a single return value. For redirect scenarios, if you want to pass attributes, you should use RedirectAttributes
.
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