[英]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";
}
The difference is only semantic. 区别仅在于语义。 If you do not create the
ModelAndView
object Spring will do it for you. 如果不创建
ModelAndView
对象,Spring将为您完成。
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. 通常,第二种方法是可取的,因为它更易于进行单元测试,尤其是当您通过
Map
而不是模型时。
EDIT To clarify on testing (based on jUnit
). 编辑澄清测试(基于
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 这使我们可以创建测试,甚至不知道涉及
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"));
}
This example is based on a Map
, but could also be a ModelMap
or even Model
if you preferred. 此示例基于
Map
,但如果您愿意,也可以是ModelMap
甚至是Model
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.