Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between redirect and redirect inside modelandview

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

like image 343
Monicka Akilan Avatar asked Oct 22 '13 11:10

Monicka Akilan


People also ask

What is the difference between forward and redirect in Spring MVC?

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.


1 Answers

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.

like image 182
Debojit Saikia Avatar answered Oct 26 '22 19:10

Debojit Saikia