Question

I have just learnt Spring MVC webflow. I am confused with this:

return new ModelAndView("test");
return new ModelAndView("redirect:test");

Is the redirect one just like response.sendRedirect()? And I just check the Spring reference, actually, the return new RedirectView() does the same as response.sendRedirect(). So what's difference between these three?

Was it helpful?

Solution

If you want to compare ModelAndView("test") and ModelAndView("redirect:test") to servlet framework. The first one will be similar to RequestDispatcher and the latter will be similar to request.sendRedirect() If you want to know the difference between requestdispatcher and sendredirect, there's the answer for that

Even though the end result of "redirect:test" is to call HttpServletResponse.sendRedirect(), RedirectView object gives you convenience and a little bit more functionalities.
IMO, using servlet API directly in the framework is probably not a good idea except you want to hack some stuff or workaround something.

The RedirectView issues an HttpServletResponse.sendRedirect() call that returns to the client browser as an HTTP redirect. By default all model attributes are considered to be exposed as URI template variables in the redirect URL. Of the remaining attributes those that are primitive types or collections/arrays of primitive types are automatically appended as query parameters.
http://docs.spring.io/spring/docs/3.1.x/spring-framework-reference/html/mvc.html

Anyway, in spring MVC, there are ususally more than one way to do the same thing. It's just the matter of coding style. For example,

public String doSomething(Model model){
    return "test";
}
public ModelAndView i_am_similar_to_doSomething(){
    return new ModelAndView("test");
}

//You can guess that you can do the same thing with redirect.

There are some more ways to do something like this but my suggestion is that try to stick to the same style for the whole application.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top