创建新的modelandview或将模型作为方法参数传递有什么区别

Nim*_*sky 5 java spring spring-mvc

我养成了这样做的习惯,所以在我的单元测试中我可以检查添加到模型中的内容:

@RequestMapping(value = "/Foo", method = RequestMethod.GET)
public ModelAndView goHome()
{
  ModelandView mav = new ModelAndView("foobar.jsp");
  mav.addObject("bar", new Bar());
  return mav;
}
Run Code Online (Sandbox Code Playgroud)

这是否更好:

@RequestMapping(value = "/Foo", method = RequestMethod.GET)
public String goHome(final Model model)
{
  model.addAttribute("bar", new Bar());
  return "foobar.jsp";
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*erg 6

差异只是语义上的.如果你不创建ModelAndView对象Spring将为你做.

一般来说,第二种方法更可取,因为单元测试更容易,特别是如果你通过Map而不是你的模型.


编辑澄清测试(基于jUnit).我发现以下签名更可取:

@RequestMapping(value = "/Foo", method = RequestMethod.GET)
public String goHome(final Map model) {
    model.addAttribute("bar", new Bar());
    return "foobar.jsp";
}
Run Code Online (Sandbox Code Playgroud)

这使我们可以在不知道Spring参与的情况下创建测试

@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"));
}
Run Code Online (Sandbox Code Playgroud)

此示例基于a Map,但也可以是ModelMap或者甚至Model是您喜欢的.