您遇到的情况很少发生。让我们去尝试
@RequestMapping("/edit") public String editTask(@RequestParam String id, Model model) { Task task = taskService.getTask(id); model.addAttribute("task", task); return "edit";}在这种情况下,Spring将
Model根据其创建一个对象
ModelAndViewContainer,并将其作为参数传递给您的方法。因此,如果您之前添加了模型属性,则可以在此处使用它们,而以后添加的属性也可以使用。您返回一个
String视图名称。Spring将使用带有String的String
ViewResolver来解析
jsp要呈现或转发到的视图或其他类型的视图。
有了这个
@RequestMapping("/edit") public ModelAndView editTask(@RequestParam String id, @ModelAttribute Task task) { // Retrieve task from the database task = taskService.getTask(id); ModelAndView model = new ModelAndView("edit"); model.addObject("task", task); return model;}由于的原因,Spring
@ModelAttribute将创建一个
Task对象,并在调用(反射)您的方法时将该对象作为参数传递。在
ModelAndView您创建对象,添加和回报将与被合并
ModelAndView对象中包含的
ModelAndViewContainer由Spring为您的要求进行管理。因此,您在此处添加的内容也将稍后可用。
The hitch: It appears
ModelAttributehas priority on the model
attributes, so it doesn’t get overwritten by the model attributes you add to
the
ModelAndViewobject. Actually it gets written to your
ModelAndView
object, overwriting your
"task"attribute. Remember that if you don’t
specify a
valueattribute to
@ModelAttributeannotation, it uses the type
of the argument to give it a name. For example,
Task==>
"task",
List<Task==>
taskList, etc.



