2010-08-06 43 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步: 然後我們把它作爲我們出價,就像它顯示在頁面上等等,像我一樣

我希望它可以幫助你理解這個概念。謝謝

相關問題