Java Spring MVC 中的@ModelAttribute 是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3423262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is @ModelAttribute in Spring MVC?
提问by Mohammad Adnan
What is the purpose and usage of @ModelAttribute
in Spring MVC?
@ModelAttribute
Spring MVC中的目的和用法是什么?
采纳答案by fasseg
@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:
@ModelAttribute
指的是 Model 对象的一个属性(MVC 中的 M ;)所以假设我们有一个表单,它带有一个名为“Person”的表单支持对象然后你可以让 Spring MVC 通过使用@ModelAttribute
注释将此对象提供给 Controller 方法:
public String processForm(@ModelAttribute("person") Person person){
person.getStuff();
}
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:
另一方面,注释用于定义应该是模型一部分的对象。因此,如果您想在 Model 中引用 Person 对象,可以使用以下方法:
@ModelAttribute("person")
public Person getPerson(){
return new Person();
}
This annotated method will allow access to the Person object in your View, since it gets automatically added to the Models by Spring.
这个带注释的方法将允许访问视图中的 Person 对象,因为它会被 Spring 自动添加到模型中。
回答by Christopher Yang
I know this is an old thread, but I thought I throw my hat in the ring and see if I can muddy the water a little bit more :)
我知道这是一个旧线程,但我想我把我的帽子扔进戒指,看看我是否可以再把水弄混一点:)
I found my initial struggle to understand @ModelAttribute
was a result of Spring's decision to combine several annotations into one. It became clearer once I split it into several smaller annotations:
我发现我最初难以理解@ModelAttribute
是 Spring 决定将多个注释合并为一个的结果。一旦我把它分成几个更小的注释,它就变得更清晰了:
For parameter annotations, think of @ModelAttribute
as the equivalent of @Autowired + @Qualifier
i.e. it tries to retrieve a bean with the given name from the Spring managed model. If the named bean is not found, instead of throwing an error or returning null
, it implicitly takes on the role of @Bean
i.e. Create a new instance using the default constructor and add the bean to the model.
对于参数注释,可以将其@ModelAttribute
视为@Autowired + @Qualifier
ie的等价物,它尝试从 Spring 托管模型中检索具有给定名称的 bean。如果未找到指定的 bean,它不会抛出错误或返回null
,而是隐式地承担@Bean
即使用默认构造函数创建一个新实例并将 bean 添加到模型中的角色。
For method annotations, think of @ModelAttribute
as the equivalent of @Bean + @Before
, i.e. it puts the bean constructed by user's code in the model and it's always called before a request handling method.
对于方法注解,可以认为@ModelAttribute
相当于@Bean + @Before
,即将用户代码构建的 bean 放入模型中,并且总是在请求处理方法之前调用。
Figuratively, I see @ModelAttribute
as the following (please don't take it literally!!):
形象地说,我认为@ModelAttribute
如下(请不要从字面上理解!!):
@Bean("person")
@Before
public Person createPerson(){
return new Person();
}
@RequestMapping(...)
public xxx handlePersonRequest( (@Autowired @Qualifier("person") | @Bean("person")) Person person, xxx){
...
}
As you can see, Spring made the right decision to make @ModelAttribute
an all-encompassing annotation; no one wants to see an annotation smorgasbord.
正如您所看到的,Spring 做出了正确的决定,即进行@ModelAttribute
了无所不包的注释;没有人想看到注释大杂烩。
回答by Chethan D
@ModelAttribute can be used as the method arguments / parameter or before the method declaration. The primary objective of this annotation to bind the request parameters or form fields to an model object
@ModelAttribute 可以用作方法参数/参数或方法声明之前。此注解的主要目标是将请求参数或表单字段绑定到模型对象
回答by Leang Socheat
For my style, I always use @ModelAttribute to catch object from spring form jsp. for example, I design form on jsp page, that form exist with commandName
对于我的风格,我总是使用 @ModelAttribute 从 spring 表单 jsp 中捕获对象。例如,我在jsp页面上设计表单,该表单与commandName一起存在
<form:form commandName="Book" action="" methon="post">
<form:input type="text" path="title"></form:input>
</form:form>
and I catch the object on controller with follow code
我使用以下代码在控制器上捕获对象
public String controllerPost(@ModelAttribute("Book") Book book)
and every field name of book must be match with path in sub-element of form
并且书的每个字段名称必须与表单子元素中的路径匹配
回答by Gagan
@ModelAttribute
will create a attribute with the name specified by you (@ModelAttribute("Testing") Test test) as Testing
in the given example ,Test being the bean test being the reference to the bean and Testing will be available in model so that you can further use it on jsp pages for retrieval of values that you stored in you ModelAttribute
.
@ModelAttribute
将使用您(@ModelAttribute("Testing") Test test) as Testing
在给定示例中指定的名称创建一个属性,Test 是 bean 测试是对 bean 的引用,Testing 将在模型中可用,以便您可以在 jsp 页面上进一步使用它来检索您存储的值在你ModelAttribute
。
回答by Byeon0gam
Annotation that binds a method parameter or method return value to a named model attribute, exposed to a web view.
将方法参数或方法返回值绑定到命名模型属性的注释,暴露给 Web 视图。
public String add(@ModelAttribute("specified") Model model) {
...
}
回答by Awais
This is used for data binding purposes in Spring MVC
. Let you have a jsp having a form element in it e.g
这用于 Spring 中的数据绑定目的MVC
。让你有一个包含表单元素的jsp,例如
on
JSP
在
JSP
<form:form action="test-example" method="POST" commandName="testModelAttribute"> </form:form>
<form:form action="test-example" method="POST" commandName="testModelAttribute"> </form:form>
(Spring Form method, Simple form element can also be used)
(Spring Form方法,也可以使用Simple form element)
On Controller Side
在控制器端
@RequestMapping(value = "/test-example", method = RequestMethod.POST)
public ModelAndView testExample(@ModelAttribute("testModelAttribute") TestModel testModel, Map<String, Object> map,...) {
}
Now when you will submit the form the form fields values will be available to you.
现在,当您提交表单时,表单字段值将可供您使用。
回答by Xelian
So I will try to explain it in simpler way. Let's have:
所以我会尝试用更简单的方式来解释它。让我们:
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
}
As described in the Spring MVC documentation - the @ModelAttributeannotation can be used on methodsor on method arguments. And of course we can have both use at the same time in one controller.
如 Spring MVC 文档中所述 - @ModelAttribute注释可用于方法或方法参数。当然,我们可以在一个控制器中同时使用两者。
1.Method annotation
1.方法注解
@ModelAttribute(“cities”)
public List<String> checkOptions(){
return new Arrays.asList(new[]{“Sofia”,”Pleven","Ruse”});//and so on
}
Purpose of such method is to add attribute in the model. So in our case citieskey will have the list new Arras.asList(new[]{“Sofia”,”Pleven","Ruse”})
as value in the Model (you can think of Model as map(key:value)). @ModelAttributemethods in a controller are invoked before @RequestMappingmethods, within the same controller.
这种方法的目的是在模型中添加属性。因此,在我们的案例中,城市键将列表new Arras.asList(new[]{“Sofia”,”Pleven","Ruse”})
作为模型中的值(您可以将模型视为 map(key:value))。 控制器中的@ModelAttribute方法在同一控制器内的@RequestMapping方法之前调用。
Here we want to add to the Model common information which will be used in the form to display to the user. For example it can be used to fill a HTML select:
在这里,我们要向模型添加公共信息,这些信息将在表单中使用以显示给用户。例如,它可用于填充 HTML 选择:
2.Method argument
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 personobject 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.
方法参数上的 @ModelAttribute 表示应该从模型中检索参数。因此,在这种情况下,我们希望 Model 中的 person对象作为键,我们希望获取它的值并将其放入方法参数Person person 中。如果这样不存在或(有时您拼错了 (value="persson")),那么 Spring 将不会在模型中找到它,并将使用其默认值创建空的 Person 对象。然后将获取请求参数并尝试使用它们的名称将它们数据绑定到 Person 对象中。
name="Dmitrij"&countries=Lesoto&sponsor.organization="SilkRoad"&authorizedFunds=&authorizedHours=&
So we have name and it will be bind to Person.name using setName(String name). So in
所以我们有了名字,它将使用 setName(String name) 绑定到 Person.name。所以在
//..Some logic with person
we have access to this filled name with value "Dimitrij".
我们可以访问这个值为“Dimitrij”的填充名称。
Of course Spring can bind more complex objects like Lists, Maps, List of Sets of Maps and so on but behind the scene it makes the data binding magic.
当然,Spring 可以绑定更复杂的对象,如列表、地图、地图集列表等,但在幕后,它使数据绑定变得神奇。
We can have at the same time model annotated method and request method handler with @ModelAttribute in the arguments. Then we have to union the rules.
Of course we have tons of different situations - @ModelAttribute methods can also be defined in an @ControllerAdvice and so on...
我们可以同时使用带有 @ModelAttribute 参数的模型注释方法和请求方法处理程序。然后我们必须联合规则。
当然,我们有很多不同的情况——@ModelAttribute 方法也可以在@ControllerAdvice 中定义,等等......
回答by Majid Ali Khan
I know I am late to the party, but I'll quote like they say, "better be late than never". So let us get going, Everybody has their own ways to explain things, let me try to sum it up and simple it up for you in a few steps with an example; Suppose you have a simple form, form.jsp
我知道我参加聚会迟到了,但我会引用他们所说的“迟到总比不到好”。那我们开始吧,每个人都有自己的解释方式,我试着总结一下,举个例子,分几步给大家简单介绍一下;假设您有一个简单的表单 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>
path="firstName" path="lastName" These are the fields/properties in the StudentClass when the form is called their getters are called but once submitted their setters are called and their values are set in the bean that was indicated in the modelAttribute="student" in the form tag.
path="firstName" path="lastName" 这些是当表单被调用时 StudentClass 中的字段/属性,它们的 getter 被调用,但是一旦提交,它们的 setter 就会被调用,它们的值在 modelAttribute= 中指示的 bean 中设置表单标签中的“学生”。
We have StudentController that includes the following methods;
我们有包含以下方法的 StudentController;
@RequestMapping("/showForm")
public String showForm(Model theModel){ //Model is used to pass data between
//controllers and views
theModel.addAttribute("student", new Student()); //attribute name, value
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
now finally we have a form-details.jsp
现在我们终于有了一个 form-details.jsp
<b>Student Information</b>
${student.firstName}
${student.lastName}
So back to the question What is @ModelAttribute in Spring MVC? A sample definition from the source for you, http://www.baeldung.com/spring-mvc-and-the-modelattribute-annotationThe @ModelAttributeis an annotation that binds a method parameter or method return value to a named model attribute and then exposes it to a web view.
那么回到 Spring MVC 中的 @ModelAttribute 是什么的问题?从源为您的样品定义, http://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation的@ModelAttribute是一个注释结合的方法参数或方法返回值来命名模型属性然后将其公开给 Web 视图。
What actually happens is it gets all the values of your form those were submitted by it and then holds them for you to bind or assign them to the object. It works same like the @RequestParameterwhere we only get a parameter and assign the value to some field. Only difference is @ModelAttributeholds all form data rather than a single parameter. It creates a bean for you that holds form submitted data to be used by the developer later on.
实际发生的是,它获取表单提交的所有值,然后保存它们以供您绑定或分配给对象。它的工作原理与@RequestParameter 一样,我们只获取一个参数并将值分配给某个字段。唯一的区别是@ModelAttribute保存所有表单数据而不是单个参数。它为您创建一个 bean,用于保存表单提交的数据,供开发人员稍后使用。
To recap the whole thing. Step 1 : A request is sent and our method showForm runs and a model, a temporary bean is set with the name student is forwarded to the form. theModel.addAttribute("student", new Student());
回顾整个事情。第 1 步:发送一个请求,我们的方法 showForm 运行,一个模型,一个名为 student 的临时 bean 被转发到表单。 theModel.addAttribute("student", new Student());
Step 2 : modelAttribute="student"on form submission model changes the student and now it holds all parameters of the form
第 2 步: 表单提交模型上的modelAttribute="student"更改了学生,现在它保存了表单的所有参数
Step 3 : @ModelAttribute("student") Student theStudentWe fetch the values being hold by @ModelAttributeand assign the whole bean/object to Student.
第 3 步: @ModelAttribute("student") Student theStudent我们获取@ModelAttribute保存的值并将整个 bean/对象分配给 Student。
Step 4 : And then we use it as we bid, just like showing it on the page etc like I did
第 4 步:然后我们在出价时使用它,就像我那样在页面上展示它一样
I hope it helps you to understand the concept. Thanks
我希望它可以帮助您理解这个概念。谢谢
回答by Ragu Venkatesan
@ModelAttribute simply binds the value from jsp fields to Pojo calss to perform our logic in controller class. If you are familiar with struts, then this is like populating the formbean object upon submission.
@ModelAttribute 只是将来自 jsp 字段的值绑定到 Pojo 类来执行我们在控制器类中的逻辑。如果您熟悉 struts,那么这就像在提交时填充 formbean 对象。