• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

which is better ModelAndView or string return with controller

 
kartik hedau
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all
i am newbie in spring MVC.
i want to know which is better way,either to return ModelAndView or just return String with controller?? I have implemented simple login demo with both way and both are working well.




 
Naresh Chaurasia
Ranch Hand
Posts: 361
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Returning ModelAndView is better choice, as you can pass values from controller to target JSPs. Check out the following link for example: Spring MVC
 
Nam Ha Minh
Ranch Hand
Posts: 504
Eclipse IDE Firefox Browser Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
kartik hedau wrote:Hi all
i am newbie in spring MVC.
i want to know which is better way,either to return ModelAndView or just return String with controller?? I have implemented simple login demo with both way and both are working well.


Well, in my opinion, it depends on a particular context. Sometimes I find returning a String is useful, sometimes returning a ModelAndView object is preferred. It's flexible, depending one's need and habit.
 
Bill Gorder
Bartender
Posts: 1682
7
Android IntelliJ IDE Linux Mac OS X Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I pretty much always return a String. Never a ModelAndView.

If I need a Model I just pass it in as a parameter

In the above code snippet I can add any thing I need to the model provided and it will be available to the view for rendering.


More often though you pass in a model attribute



In this case if its a POST you will probably get a Person object populated from the form being submitted. But if the person attribute is not there, then Spring will call the default constructor on the Person object and pass in a new instance of Person and automatically add it to the model for use in the view. In either event there is never a need to return a ModelAndView anymore.
 
kartik hedau
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, in my opinion, it depends on a particular context. Sometimes I find returning a String is useful, sometimes returning a ModelAndView object is preferred. It's flexible, depending one's need and habit.



thank you for your thoughts, but can you elaborate more on " depends on a particular context"
 
Bill Gorder
Bartender
Posts: 1682
7
Android IntelliJ IDE Linux Mac OS X Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is the beauty, you can choose whatever you are most comfortable with.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic