Spring MVC中@ModelAttribute的目的和用法是什么?


当前回答

以任何web应用程序为例,无论是Gmail还是Facebook或Instagram或任何其他web应用程序,都是关于最终用户和应用程序或UI和后端应用程序之间交换数据或信息。即使在Spring MVC世界中,也有两种交换数据的方式:

从控制器到UI,以及 从UI到控制器。

这里我们感兴趣的是数据如何从UI传递到Controller。这也可以通过两种方式来实现:

使用HTML表单 使用查询参数。

使用HTML表单: 考虑下面的场景,

当我们从web浏览器提交表单数据时,我们可以在Controller类中作为对象访问该数据。当我们提交一个HTML表单时,Spring容器做了四件事。它将,

first read all the data that is submitted that comes in the request using the request.getParameter method. once it reads them, it will convert them into the appropriate Java type using integer.parseInt, double.parseDouble and all the other parse methods that are available based on the data type of the data. once parsed, it will create a object of the model class that we created. For example, in this scenario, it is the user information that is being submitted and we create a class called User, which the Container will create an object of and it will set all the values that come in automatically into that object. it will then handover that object by setting the values to the Controller.

为了让整个计划顺利进行,我们必须遵循一定的步骤。

We first need to define a model class, like User, in which the number of fields should exactly match the number of fields in the HTML form. Also, the names that we use in the HTML form should match the names that we have in the Java class. These two are very important. Names should match, the number of fields in the form should match the number of fields in the class that we create. Once we do that, the Container will automatically read the data that comes in, creates an object of this model, sets the values and it hands it over to the Controller. To read those values inside the Controller, we use the @ModelAttribute annotation on the method parameters. When we create methods in the Controller, we are going to use the @ModelAttribute and add a parameter to it which will automatically have this object given by the Container.

下面是一个注册用户的示例代码:

@RequestMapping(value = "registerUser", method = RequestMethod.POST)
public String registerUser(@ModelAttribute("user") User user, ModelMap model) {
    model.addAttribute("user", user);
    return "regResult";
}

希望这个图解解释对你有帮助!

其他回答

@ModelAttribute将使用您指定的名称(@ModelAttribute(“Testing”)Test Test)创建一个属性,在给定的示例中作为Testing,Test是bean测试,是bean的引用,而Testing将在模型中可用,以便您可以进一步在jsp页面上使用它来检索存储在ModelAttribute中的值。

我知道我来晚了,但我要引用他们的话, “迟到总比不到好”。让我们开始吧, 每个人都有自己解释事情的方式,让我试着总结一下,用一个例子用几个步骤为你简单解释一下; 假设你有一个简单的表单form.jsp:

<form:form action="processForm" modelAttribute="student">
  First Name : <form:input path="firstName" /> 
  <br/><br/>
  Last Name : <form:input path="lastName" />
  <br/><br/>
  <input type="submit" value="submit"/>
</form:form>

<form:input path="firstName" /> <form:input path="lastName" />这些是Student类中的字段/属性。当表单被调用/初始化时,它们的getter被调用。在表单提交时,它们的setter被调用,它们的值在表单标记中用modelAttribute="student"指示的bean中传输。

我们有StudentController,它包含以下方法:

@RequestMapping("/showForm")
// `Model` is used to pass data between controllers and views
public String showForm(Model theModel) {
    // attribute name, value
    theModel.addAttribute("student", new Student());
    return "form";
}
   
@RequestMapping("/processForm")
public String processForm(@ModelAttribute("student") Student theStudent) {
    System.out.println("theStudent :"+ theStudent.getLastName());
    return "form-details";
}

//@ModelAttribute("student") Student theStudent
//Spring automatically populates the object data with form data 
//all behind the scenes

现在我们终于有了一个form-details.jsp:

<b>Student Information</b>
${student.firstName}
${student.lastName}

回到这个问题,Spring MVC中的@ModelAttribute是什么? 一个来自源代码的示例定义, http://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation @ModelAttribute是一个注释,它将一个方法参数或方法返回值绑定到一个命名的模型属性,然后将它公开给一个web视图。

实际发生的是,它获取表单的所有值那些由它提交的值,然后保存它们供你绑定或赋值给对象。它的工作方式类似于@RequestParameter,我们只获得一个参数并将值分配给某个方法参数。 区别在于@ModelAttribute保存所有表单数据,而不是单个参数。它为您创建一个bean,其中包含表单中提交的数据。

概括一下整件事:

步骤1: 请求被发送,我们的方法showForm()运行,一个模型,一个临时bean,被设置为student并转发给表单: 这个模型。addAttribute("student", new student ());

步骤2: 表单属性modelAttribute="student"定义了在表单提交时,模型将更新学生并保存表单的所有参数。

步骤3: 在表单提交时,使用参数@ModelAttribute("student")调用processForm()方法:使用modelAttribute="student"的表单中保存的值被提取并分配给student对象中的字段。

步骤4: 然后我们使用它,因为我们出价,就像在页面上显示它等,就像我做的

我希望它能帮助你理解这个概念。谢谢

所以我会试着用更简单的方式来解释。让我们有:

public class Person {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(final String name) {
        this.name = name;
    }
}

正如Spring MVC文档中所描述的那样——@ModelAttribute注释可以用于方法或方法参数。当然我们可以在一个控制器中同时使用这两种方法。

1.方法注释

@ModelAttribute("cities")
 public List<String> checkOptions(){
 return new Arrays.asList(new[]{"Sofia","Pleven","Ruse"});//and so on
}

这种方法的目的是在模型中添加属性。因此,在我们的案例中,cities key将拥有列表new Arrays.asList(new[]{"Sofia","Pleven","Ruse"})作为模型中的值(您可以将模型看作map(key:value))。在同一个控制器中,在@RequestMapping方法之前调用控制器中的@ModelAttribute方法。

在这里,我们希望向Model添加将在表单中用于显示给用户的公共信息。例如,它可以用来填充HTML选择:

2.方法参数

public String findPerson(@ModelAttriute(value="person") Person person) {
    //..Some logic with person
    return "person.jsp";
}

An @ModelAttribute on a method argument indicates the argument should be retrieved from the model. So in this case we expect that we have in the Model person object as key and we want to get its value and put it to the method argument Person person. If such does not exists or (sometimes you misspell the (value="persson")) then Spring will not find it in the Model and will create empty Person object using its defaults. Then will take the request parameters and try to data bind them in the Person object using their names.

name="Dmitrij"&countries=Lesoto&sponsor.organization="SilkRoad"&authorizedFunds=&authorizedHours=&

我们有了name,它会使用setName(String name)绑定到person。name。因此,在

//..Some logic with person

我们可以访问这个值为“Dimitrij”的填充名称。

当然,Spring可以绑定更复杂的对象,比如List、map、List Of Sets Of Maps等等,但在幕后,它实现了数据绑定的魔力。

我们可以同时拥有带模型注释的方法和参数中带有@ModelAttribute的请求方法处理程序。那我们就得统一规则。 当然,我们有很多不同的情况——@ModelAttribute方法也可以在@ControllerAdvice中定义,等等……

以任何web应用程序为例,无论是Gmail还是Facebook或Instagram或任何其他web应用程序,都是关于最终用户和应用程序或UI和后端应用程序之间交换数据或信息。即使在Spring MVC世界中,也有两种交换数据的方式:

从控制器到UI,以及 从UI到控制器。

这里我们感兴趣的是数据如何从UI传递到Controller。这也可以通过两种方式来实现:

使用HTML表单 使用查询参数。

使用HTML表单: 考虑下面的场景,

当我们从web浏览器提交表单数据时,我们可以在Controller类中作为对象访问该数据。当我们提交一个HTML表单时,Spring容器做了四件事。它将,

first read all the data that is submitted that comes in the request using the request.getParameter method. once it reads them, it will convert them into the appropriate Java type using integer.parseInt, double.parseDouble and all the other parse methods that are available based on the data type of the data. once parsed, it will create a object of the model class that we created. For example, in this scenario, it is the user information that is being submitted and we create a class called User, which the Container will create an object of and it will set all the values that come in automatically into that object. it will then handover that object by setting the values to the Controller.

为了让整个计划顺利进行,我们必须遵循一定的步骤。

We first need to define a model class, like User, in which the number of fields should exactly match the number of fields in the HTML form. Also, the names that we use in the HTML form should match the names that we have in the Java class. These two are very important. Names should match, the number of fields in the form should match the number of fields in the class that we create. Once we do that, the Container will automatically read the data that comes in, creates an object of this model, sets the values and it hands it over to the Controller. To read those values inside the Controller, we use the @ModelAttribute annotation on the method parameters. When we create methods in the Controller, we are going to use the @ModelAttribute and add a parameter to it which will automatically have this object given by the Container.

下面是一个注册用户的示例代码:

@RequestMapping(value = "registerUser", method = RequestMethod.POST)
public String registerUser(@ModelAttribute("user") User user, ModelMap model) {
    model.addAttribute("user", user);
    return "regResult";
}

希望这个图解解释对你有帮助!

@ModelAttribute只是将jsp字段的值绑定到Pojo类,以执行控制器类中的逻辑。如果您熟悉struts,那么这就像在提交时填充formbean对象。