【问题标题】:@ModelAttribute("") annotation is still working with the wrong parameter in spring mvc@ModelAttribute("") 注释仍在使用 spring mvc 中的错误参数
【发布时间】:2018-05-11 19:01:16
【问题描述】:

我正在尝试学习 spring mvc。我无法理解 @ModelAttribute 的工作原理。下面是我的控制器

@RequestMapping("/showForm")
public String showForm(Model theModel){

    Student student = new Student();
    theModel.addAttribute("testName",student); 
    return "student-form";
}

@RequestMapping("/processForm")
public String showForm(@ModelAttribute("hello") Student student){

    return "student-confirmation";
}

当我进入学生表单页面时,我创建了一个 student 对象并将其添加到属性名称为 "testName" 的模型中。然后我将表单提交给“processForm”方法。使用下面的表格

<form:form action="processForm" modelAttribute="testName">
    First Name: <form:input path="firstName" />
    Second Name: <form:input path="lastName" />

    <input type="submit" value="submit" />
</form:form>

这是我不明白的属性名称在我将对象放置到模型的位置以及我检索它的位置不匹配。但是结果显示正确..

theModel.addAttribute("testName",student);   //Here it is testName
@ModelAttribute("hello")  Student student    //Here it is hello

学生确认.jsp

First Name :  ${hello.firstName}
Last Name :  ${hello.lastName}

【问题讨论】:

    标签: spring spring-mvc model modelattribute


    【解决方案1】:

    Student 模型在提交表单后自动填充,因为您已将 testName 设置为模型属性:

    theModel.addAttribute("testName",student); 
    

    JSP:

    <form:form action="processForm" modelAttribute="testName">
    <form:input path="firstName" />
    

    所以 Spring 将 Student 字段 firstName 与带有路径的表单文本输入匹配: path="firstName" 。

    提交后:

    @RequestMapping("/processForm")
    public String showForm(@ModelAttribute("hello") Student student){
    

    @ModelAttribute("hello") 不是必需的,Student 匹配 自动。

    您只需更改模型的参考名称。然后您可以在 JSP 中使用 ${hello.firstName} 从模型中获取值。

    有关@ModelAttribute 的更多信息,您可以阅读@ModelAttribute Annotation As a Method Argument

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-12
      • 1970-01-01
      • 2012-12-04
      • 2017-08-03
      • 1970-01-01
      • 2019-09-02
      • 1970-01-01
      • 2012-12-03
      相关资源
      最近更新 更多