I got into the habit of doing this, so that in my unit tests I could check what had been added to model:
@RequestMapping(value = "/Foo", method = RequestMethod.GET)
public ModelAndView goHome()
{
ModelandView mav = new ModelAndView("foobar.jsp");
mav.addObject("bar", new Bar());
return mav;
}
Is this better:
@RequestMapping(value = "/Foo", method = RequestMethod.GET)
public String goHome(final Model model)
{
model.addAttribute("bar", new Bar());
return "foobar.jsp";
}
The difference is only semantic. If you do not create the ModelAndView
object Spring will do it for you.
Generally the second approach is preferable since it's a lot easier to unit test, especially if you pass a Map
instead of your model.
EDIT To clarify on testing (based on jUnit
). I find the following signature preferable:
@RequestMapping(value = "/Foo", method = RequestMethod.GET)
public String goHome(final Map model) {
model.addAttribute("bar", new Bar());
return "foobar.jsp";
}
This allows us to create a test without even knowing Spring
is involved
@Test
public void testGoHome() {
// Setup
Controller controller = ...
Map<String, Bar> model = new HashMap<String, Bar>();
// Test
assertEquals("foobar.jsp", controller.goHome(model));
assertNotNull(model.get("bar"));
}
This example is based on a Map
, but could also be a ModelMap
or even Model
if you preferred.
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