I'm struggling with the best way to reuse my logic for creating view models, particularly when these models are non-trivial. For example, I have a view that expects certain model data to be present, let's say:
- a list of Person objects
- a boolean "editable" flag
- a string message
I have String constants for the names of these things in the model:
When I need to create a ModelAndView, I do this:Code:ViewConstants.MODEL_PEOPLE = "people"; ViewConstants.MODEL_EDITABLE = "editable"; ViewConstants.MODEL_MESSAGE = "message";
However, I need to generate this type of "model and view" from multiple controllers (using different model objects in each case), so what's the best way to share this logic? Solutions I've come up with so far are:Code:Map model = new HashMap(); model.put(ViewConstants.MODEL_PEOPLE, somePeople); model.put(ViewConstants.MODEL_EDITABLE, someBooleanObject); model.put(ViewConstants.MODEL_MESSAGE, someMessage); /* maybe some other stuff gets added to the model here, possibly * looked up by a service known to the controller */ ModelAndView modelAndView = new ModelAndView("myView", model);
- having a method in one of the controllers that takes the model objects and returns the ModelAndView, but this means the other controllers have to have this controller injected into them as a dependency, which is ugly and also complicates unit testing, as I have to create and set up a lot more mock objects
- subclassing ModelAndView to create say PersonModelAndView, whose constructor takes all the necessary model data and services as arguments (I just thought of this approach, so don't know the pros and cons yet)
What do other people do in this situation? Is there a Spring best practice?


Reply With Quote