代码之家  ›  专栏  ›  技术社区  ›  Stacky

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

  •  0
  • Stacky  · 技术社区  · 6 年前

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

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

    @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

    即使a“ new ModelAndView("student", "command", new Student()) 对象不是由GET方法返回的,如示例中所示,“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 回复  |  直到 6 年前
        1
  •  1
  •   user4602302 user4602302    6 年前

    表单标记的默认modelattribute为command。在引用的示例中,“魔法”发生在:

    @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构造函数的第二个和第三个参数负责将新的学生对象绑定到表单标记默认modelattribute“command”

    在post接收方法中,modelattribute注释“SpringWeb”的名称值

    @ModelAttribute("SpringWeb") Student student
    

    也可以删除

    @ModelAttribute Student student
    
        2
  •  0
  •   Stacky    6 年前

    在进一步研究之后,我发现“SpringWeb”只是一些在线教程中为提交的“表单”的model属性指定的默认名称。这在许多其他教程中都有复制。Spring在注释@ModelAttribute(“xyz”)中为模型属性命名。

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