Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between creating a new modelandview or passing in a model as method parameter

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";
}
like image 745
NimChimpsky Avatar asked Feb 20 '12 14:02

NimChimpsky


1 Answers

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.

like image 147
Johan Sjöberg Avatar answered Oct 22 '22 07:10

Johan Sjöberg