2013-03-05 21 views
0

嗨我想知道什麼是使用@ModelAttribute 的目的爲何使用什麼是使用@ModelAttribute

@RequestMapping(value="") 
public String index(@ModelAttribute("before") Before b) { 
    System.out.println(b.getBeforeString()); 
    return "home/index"; 
} 

@ModelAttribute("before") 
public Before before() { 
    return new Before(); 
} 

時,我可以使用

@RequestMapping(value="") 
public String index() { 
    Before b = new Before(); 
    System.out.println(b.getBeforeString()); 
    return "home/index"; 
} 

回答

3

@ModelAttribute用於填充的目的進入MVC模型以供隨後在視圖中使用。這不是把東西模型(這可以通過直接藏漢代碼來完成)的唯一途徑,但它是增加@RequestMapping方法指定參數時,或從方法的返回值,除其他事項外的便捷方式。

在每個在同一控制器類中調用的@RequestMapping方法之前調用用@ModelAttribute註釋的方法。這通常用於爲表單顯示只讀組件 - 例如選擇列表的值。 (http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#mvc-ann-modelattrib-methods) - 或(從數據存儲加載例如)製備豆之前結合傳入請求的值。

所以,在你的第一個例子...

@ModelAttribute("before") 
public Before before() { 
    return new Before(); 
} 
@RequestMapping(value="") 
public String index(@ModelAttribute("before") Before b) { 
    System.out.println(b.getBeforeString()); 
    return "home/index"; 
} 

...的before()方法將被調用第一,把Before例如與「前」的名義模型。接下來,index(...)方法將被調用,並接受同樣的Before實例(因爲它也使用模型屬性名稱「前」) - 但它現在將值從請求,該請求PARAM名稱映射到屬性名之前填充。 (旁白:這也許是你正打算不是如果這是真的,你想,你應該考慮增加一個BindingResult作爲第二對Arg的索引方法來捕捉任何綁定錯誤(http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#mvc-ann-arguments子彈點17)的東西。)。

在此之後,@ModelAttribute anntotation在index(...)也將導致Before實例「之前」出現一個名爲模型在一個視圖使用:「/首頁/索引」。

(值得一提的是:如果你沒有足夠的before()方法可言,你index()方法將收到其無參數的構造函數創建,然後與傳入請求的值popuplated的Before實例它仍然會隨後把它與

你的第二個代碼片段「前」,用於下一個視圖中使用。)這個名字的模型......

@RequestMapping(value="") 
public String index() { 
    Before b = new Before(); 
    System.out.println(b.getBeforeString()); 
    return "home/index"; 
} 

...實際上並沒有加入Before到模型在所有,所以它不會在視圖中可用。如果您在模型中要之前在這裏使用:

@RequestMapping(value="") 
public String index(Model uiModel) { 
    Before b = new Before(); 
    System.out.println(b.getBeforeString()); 
    uiModel.addAttribute("beforeName", b); // will add to model with name "beforeName" 
    uiModel.addAttribute(b) // will add to model with a default name (lower-cased simple type name by convention), ie: "before" 
    return "home/index"; 
} 

HTH

+0

所以,如果'@ ModelAttribute'傳遞對象查看,我怎麼能讀這個對象,在視圖中這種方法嗎? – 2013-03-06 17:43:09

+1

一切都在名稱模型中進行。用'@ModelAttribute(「之前的)'之前'這個名字是'before'(小寫)。在你的JSP上網本與EL'{}之前$'和道具用'$ {before.beforeString}' – sbk 2013-03-07 01:54:16