默认的“SpringWeb”模型属性用法和文档

时间:2018-04-05 23:55:17

标签: java spring spring-mvc model-view-controller model

在许多教程和其他地方我注意到,在提交表单时,使用名为“SpringWeb”的默认模型属性将所有jsp元素映射到java POJO。

例如,在以下教程中,@ModelAttribute("SpringWeb")映射到Student对象。

@RequestMapping(value = "/addStudent", method = RequestMethod.POST)
      public String addStudent(@ModelAttribute("SpringWeb")Student student, 

   ModelMap model) {
      model.addAttribute("name", student.getName());
      model.addAttribute("age", student.getAge());
      model.addAttribute("id", student.getId());

      return "result";
   } 

@RequestMapping(value = "/student", method = RequestMethod.GET)
   public ModelAndView student() {
      return new ModelAndView("student", "command", new Student());
   }

http://www.tutorialspoint.com/spring/spring_mvc_form_handling_example.htm

即使GET方法没有返回“new ModelAndView("student", "command", new Student())”对象,如表中所示,当回发表单时,“SpringWeb”模型属性仍然存在。 例如 - 在GET请求中,如果我写model.addAttribute ("xyz", "123)并且只返回视图名称,并且我没有使用jsp标记中的“path”映射表单字段。当表单被发回时,表单字段仍将通过“SpringWeb”映射到java对象。

在github中也没有“SpringWeb”的搜索结果: https://github.com/spring-projects/spring-framework/search?utf8=%E2%9C%93&q=SpringWeb&type=

我知道可以使用自定义模型属性并将其映射到表单元素,而不是使用@ModelAttribute("SpringWeb")。 但是,我在stackoverflow中找不到任何相关的问题,这些问题可以详细解释“SpringWeb”是什么以及使用它是不是一个好的或坏的做法?

我在“POST”请求上调试了模型对象,发现“SpringWeb”在“BindingAwareModelMap”模型对象中自动作为“键”和“值”对出现。但是,我在下面的链接中找不到任何与“SpringWeb”相关的文档。

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/validation/support/BindingAwareModelMap.html

什么是“SpringWeb”?我目前的理解是它是一个“全能”模型属性,在提交表单时由spring自动映射。 如果是,那么它是如何被发现并决定在没有任何文件的情况下使用它的? (至少我找不到)

2 个答案:

答案 0 :(得分:1)

form-tags默认modelattribute是命令。在引用的例子中,“魔法”发生在那里:

@RequestMapping(value = "/student", method = RequestMethod.GET)
public ModelAndView student() {
    // the second and third parameter:
    // a new Student is binded to the form-tags default modelattribute
    return new ModelAndView("student", "command", new Student());
}

ModelAndView的构造函数的第二个和第三个参数负责将新的Student-Object绑定到form-tags默认的modelattribute“command”

在post-receiving-method中,modelattribute-annotation“SpringWeb”的名称值

@ModelAttribute("SpringWeb") Student student

也可以删除

@ModelAttribute Student student

答案 1 :(得分:0)

经过更多的探索,我发现了#34; SpringWeb"只不过是提交的"表格"的模型属性的默认名称。在一些在线教程中。这已在许多其他教程中复制过。 Spring将注释中的名称@ModelAttribute(" xyz")提供给模型属性。

事实上,在许多情况下,并不真正需要@ModelAttribute注释。有关此注释用法的更多详细信息,请访问: @ModelAttribute annotation, when to use it?