2010-08-06 104 views
300

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

+45

阅读文档:http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-modelattrib和http:// static。 springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/bind/annotation/ModelAttribute.html – skaffman 2010-08-06 11:25:08

+25

我认为这是一个有用的问题,因为它可以让读者获得更多的信息(包括例子)比Spring的官方文档提供的更多 – anton1980 2014-08-26 21:24:53

+2

在这里检查这篇文章。 http://thespringthing.blogspot.com/2010/11/how-does-modelattribute-work.html – praveenj 2015-06-24 22:45:14

回答

354

@ModelAttribute指模型对象(M在MVC)的属性 让我们说我们有一个表单支持对象的形式,被称为“人” 然后你就可以让Spring MVC提供此对象通过使用@ModelAttribute注释的控制器方法:

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

Check here为一个例子(春2.5),也参见"Using @ModelAttribute on a method argument"(春季3.1)。

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

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

此批注的方法将允许访问视图中的Person对象,因为它被自动添加到模型由春天。

请参阅"Using @ModelAttribute on a method"(Spring 3.1)。

希望这有助于。

+4

@fasseg在第一种情况下,你实际上不需要'@ ModelAttribute'。 – 2015-03-17 21:15:38

+0

@Neil什么时候你需要在方法属性中使用'@ ModelAttribute'? – Ryan 2015-06-12 22:25:09

+3

@Ryan查看http://stackoverflow.com/questions/8688135/modelattribute-annotation-when-to-use-it/26916920#26916920 – 2015-06-12 22:33:13

111

我知道这是一个古老的线程,但我想我把我的帽子环,看看我能搅浑了水多一点点:)

我发现我最初很难理解@ModelAttribute是Spring决定将几个注释合并为一个。一旦我将它分成几个较小的注释,就会变得更加清晰:

对于参数注释,可以将@ModelAttribute等效为@Autowired + @Qualifier,即它试图从Spring托管模型中检索具有给定名称的bean。如果未找到指定的bean,则不会抛出错误或返回错误,而是隐式地扮演@Bean的角色,即使用默认构造函数创建新实例并将该bean添加到模型中。

对于方法注解,认为@ModelAttribute等效于@Bean + @Before,即它将由用户代码构造的bean放入模型中,并且它始终在请求处理方法之前调用。

打个比方,我看到@ModelAttribute为以下内容(请不要把它从字面上!!):

@Bean("person") 
@Before 
public Person createPerson(){ 
    return new Person(); 
} 

@RequestMapping(...) 
public xxx handlePersonRequest((@Autowired @Qualifier("person") | @Bean("person")) Person person, xxx){ 
    ... 
} 

正如你所看到的,春天做出了正确的决定,使@ModelAttribute一个包罗万象的注释;没有人想看到一个注释大杂烩。

+1

嗯,@Bean默认是单身。我不确定这里适用相同的概念。 – Zombies 2013-08-14 23:06:33

+9

绝对不是。我只是使用更简单的注释来解释这个复杂的注释。请从概念上解释我的解释,而不是字面意思。 – 2013-08-15 01:01:56

+2

@僵尸添加'@Scope(“request”)'then :) – OrangeDog 2016-06-27 16:15:21

19

对于我的风格,我总是使用@ModelAttribute从spring窗体jsp中捕捉对象。例如,我的JSP页面设计形式,这种形式与命令名

<form:form commandName="Book" action="" methon="post"> 
     <form:input type="text" path="title"></form:input> 
</form:form> 

存在的,我捕捉对象上的控制器与后续代码

public String controllerPost(@ModelAttribute("Book") Book book) 

和书籍的各个领域名称必须匹配路径在表格的子元素

+2

'catch'动词完全描述了@ ModelAttribute所做的工作。尼斯。 – Eddy 2016-12-13 02:49:50

+1

年度最佳答案。 – 2017-06-16 07:42:30

-1

@ModelAttribute将创建与您(@ModelAttribute("Testing") Test test) as Testing在给定的例子指定名称的属性,测试是豆测试作为参考豆和测试将在模型中可用,让你在f进一步在jsp页面上使用它来检索您存储在您的值ModelAttribute

3

将方法参数或方法返回值绑定到暴露给Web视图的命名模型属性的注释。

private String add(@ModelAttribute("specified ") Model model) { 
    ... 
} 
3

这是在Spring MVC中用于数据绑定的目的。让你有一个表单元素一个jsp中它如

JSP

<form:form action="test-example" method="POST" commandName="testModelAttribute"> </form:form>

(Spring表单方法,也可以用简单的表单元素)

在控制器端

@RequestMapping(value = "/test-example", method = RequestMethod.POST) 
public ModelAndView testExample(@ModelAttribute("testModelAttribute") TestModel testModel, Map<String, Object> map,...) { 

} 

现在,当您提交表单时,您可以使用表单字段值。

10

所以我会尝试以更简单的方式解释它。让我们:

public class Person { 
    private String name; 

    public String getName() { 
     return name; 
    } 

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

由于Spring MVC的文档中描述 - 该@ModelAttribute批注可在方法方法的参数使用。当然,我们可以同时在一个控制器中使用。

1.Method注释

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

这种方法的目的是在模型中添加属性。因此,在我们的案例中,城市键将在模型中具有值为new Arras.asList(new[]{“Sofia”,”Pleven","Ruse”})的列表(您可以将模型视为map(键:值))。 @ModelAttribute控制器中的方法在同一控制器内的@RequestMapping方法之前调用。

在这里,我们想添加到模型中的常用信息,这些信息将在表单中用于显示给用户。例如,它可用于填充HTML选择:

enter image description here

2.Method参数

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

的@ModelAttribute上的方法参数指示参数应该从模型中检索。因此,在这种情况下,我们期望我们在对象中具有关键字,并且我们希望获得其值并将其置于方法参数人员。如果不存在或(有时候你拼错了(value =“persson”))。然后Spring将不会在模型中找到它,并使用其默认值创建空的Person对象。然后将采取请求参数并尝试使用它们的名称将数据绑定到Person对象中。

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

因此,我们有名称,它将使用setName(String name)绑定到Person.name。所以在

//..Some logic with person 

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

当然

弹簧可以绑定更复杂的对象,如列表,地图,地图的设置等的名单,但幕后它使数据绑定的魔力。

  1. 我们可以在参数中使用@ModelAttribute同时具有模型注释的方法和请求方法处理程序。那么我们必须将规则结合起来。

  2. 我们当然有一大堆不同的情况 - @ModelAttribute方法也可以在@ControllerAdvice定义等等...

2

我知道我迟到了,但我我会像他们说的那样引用, “最好迟到”。所以,让我们开始吧,每个人都有自己的方式来解释事情,让我试着总结一下,通过几个例子,通过几个步骤简单起见, 假设你一个简单的形式,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> 

路径=“名字” 路径=“姓氏” 这些在StudentClass 字段/属性时的形式被称为他们的干将被称为但一旦提交,他们的setter被调用,并且它们的值在formAttribute =“student”中的form标签中指示的bean中设置。

我们的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 

现在我们终于有一个表格,details.jsp

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

所以回到刚才的问题是什么@ModelAttribute在Spring MVC? 从源为您的样品定义, http://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation@ModelAttribute是结合的方法参数或方法返回值来命名模型属性的注释,然后将其暴露到Web视图。

实际发生的是它获取由它提交的所有ur表单的值,然后让它们为你绑定或将它们分配给对象。 它的工作原理与@RequestParameter一样,我们只得到一个参数并将值赋给某个​​字段。 唯一区别是@ModelAttribute保存所有表单数据而不是单个参数。它为您创建一个bean,用于保存表单提交的数据以供开发人员稍后使用。

回顾一下。 步骤1: 发送请求,并且我们的方法showForm运行,并设置一个模型,临时bean的名称为学生,并将其转发给表单。 theModel.addAttribute(“student”,new Student());

步骤2: 的ModelAttribute = “学生” 上表单提交模型改变学生,现在,它保持该表格的所有参数

步骤3: @ModelAttribute(”学生“)学生学生 我们拿取的值由@模型属性并将整个bean /对象分配给Student。

第4步: 然后我们把它作为我们出价,就像它显示在页面上等等,像我一样

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

相关问题