Spring MVC 中的@ModelAttribute 是什么? [英] What is @ModelAttribute in Spring MVC?

查看:43
本文介绍了Spring MVC 中的@ModelAttribute 是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@ModelAttribute 在 Spring MVC 中的用途和用途是什么?

What is the purpose and usage of @ModelAttribute in Spring MVC?

推荐答案

@ModelAttribute 指的是Model对象的一个​​属性(MVC中的M;)所以假设我们有一个表单,它带有一个名为Person"的表单支持对象然后,您可以让 Spring MVC 使用 @ModelAttribute 批注将此对象提供给 Controller 方法:

@ModelAttribute refers to a property of the Model object (the M in MVC ;) so let's say we have a form with a form backing object that is called "Person" Then you can have Spring MVC supply this object to a Controller method by using the @ModelAttribute annotation:

public String processForm(@ModelAttribute("person") Person person){
    person.getStuff();
}

另一方面,注解用于定义应该是模型一部分的对象.所以如果你想在 Model 中引用一个 Person 对象,你可以使用下面的方法:

On the other hand the annotation is used to define objects which should be part of a Model. So if you want to have a Person object referenced in the Model you can use the following method:

@ModelAttribute("person")
public Person getPerson(){
    return new Person();
}

这个带注释的方法将允许访问您视图中的 Person 对象,因为它会被 Spring 自动添加到模型中.

This annotated method will allow access to the Person object in your View, since it gets automatically added to the Models by Spring.

参见 使用@ModelAttribute".

这篇关于Spring MVC 中的@ModelAttribute 是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆