在Spring MVC中return ModelAndView和return String有什么区别? [英] What is the difference between return ModelAndView and return String in Spring MVC?
问题描述
我想知道ModelAndView和String之间的区别.
I want to know the different between ModelAndView and String.
@RequestMapping(value="/")
public ModelAndView mainPage() {
return new ModelAndView("home");
}
第二段代码是关于返回String的:
and the second piece of code is about returning String:
@RequestMapping(value="/")
public String mainPage() {
return "home";
}
推荐答案
您可以从控制器返回很多东西,Spring会自动尝试从那里推断出要做什么.
You can return many things from a controller, and Spring will automatically try to deduce what to do from there.
当返回ModelAndView时,所有需要从控制器传递的信息都嵌入其中.没有惊喜.
When you return a ModelAndView all information that needs to be passed from the controller is embedded inside it. No suprise there.
如果返回String,它将假定这是要使用的视图的名称.它将把它包装在一个ModelAndView对象中,该对象具有字符串作为视图,并且还嵌入了现有模型.
If you return a String, it will assume that this is the name of the view to use. It will wrap this in a ModelAndView object with the string as the view and the existing model embedded as well.
Spring在返回类型以及参数类型上都有很多魔力". 这样一来,您便可以以更直观的方式编写代码,即以下两个示例相同:
Spring does a lot of 'magic' on the return types, but also on the parameter types. This allows you to write code in a style that is more intuitive for you, i.e. the following two examples are the same:
@RequestMapping(value="/")
public ModelAndView mainPage() {
Model m = new Model();
m.put("key", "value");
return new ModelAndView(m,"main");
}
和
@RequestMapping(value="/")
public String mainPage(Model m) {
m.put("key", "value");
return "main";
}
第二个变体稍微冗长一些,更易于单独测试.传入的模型将为空模型(除非从其他控制器转发).
This second variant is a little less verbose and easier to test separately. The model passed in will be an empty model (unless forwarded from some other controller).
这篇关于在Spring MVC中return ModelAndView和return String有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!