2012-12-03 95 views
21

使用值和綁定與JavaServer Faces之間有什麼區別,以及何時使用一個而不是另一個?爲了更清楚地說明我的問題,這裏給出幾個簡單的例子。值與綁定之間的區別

與在XHTML代碼,你就可以用 「價值」 在這裏JSF

通常情況下:

<h:form> 
    <h:inputText value="#{hello.inputText}"/> 
    <h:commandButton value="Click Me!" action="#{hello.action}"/> 
    <h:outputText value="#{hello.outputText}"/> 
</h:form> 

那麼bean是:

// Imports 
@ManagedBean(name="hello") 
@RequestScoped 
public class Hello implements Serializable { 

private String inputText; 
private String outputText; 

public void setInputText(String inputText) { 
    this.inputText = inputText; 
} 

public String getInputText() { 
    return inputText; 
} 

// Other getters and setters etc. 

// Other methods etc. 

public String action() { 

    // Do other things 

    return "success"; 
} 
} 

然而,當使用 「綁定」 的XHTML代碼是:

<h:form> 
    <h:inputText binding="#{backing_hello.inputText}"/> 
    <h:commandButton value="Click Me!" action="#{backing_hello.action}"/> 
    <h:outputText value="Hello!" binding="#{backing_hello.outputText}"/> 
</h:form> 

和correspondibg豆被稱爲後臺bean,並在這裏:

// Imports 
@ManagedBean(name="backing_hello") 
@RequestScoped 
public class Hello implements Serializable { 

private HtmlInputText inputText; 
private HtmlOutputText outputText; 

public void setInputText(HtmlInputText inputText) { 
    this.inputText = inputText; 
} 

public HtmlInputText getInputText() { 
    return inputText; 
} 

// Other getters and setters etc. 

// Other methods etc. 

public String action() { 

    // Do other things 

    return "success"; 
} 
} 

這兩個系統之間有什麼實際的區別,什麼時候使用支持bean而不是普通的bean?是否可以同時使用?

我一直在困惑這個一段時間,並會很高興有這個清理。

+0

相關:http://stackoverflow.com/questions/12506679/what -is-component-binding-in-jsf-when-it-is-is-preferred-to-be-used/12512672#12512672 – BalusC

回答

2

有時我們並不需要將UIComponent的值應用到bean屬性。例如,您可能需要訪問UIComponent並使用它,而不將其值應用於模型屬性。在這種情況下,最好使用支持bean而不是普通的bean。另一方面,在某些情況下,我們可能需要使用UIComponent的值,而不需要對它們進行編程訪問。在這種情況下,你可以使用普通的豆子。

因此,規則是隻有當您需要對視圖中聲明的組件進行編程訪問時才使用支持bean。在其他情況下,使用普通的bean。

35

value屬性代表組件的值。當您在瀏覽器中打開頁面時,您可以在文本框內看到文本

binding屬性用於將您的組件綁定到bean屬性。對於代碼中的示例,您的inputText組件以這種方式綁定到bean。

#{backing_hello.inputText}` 

這意味着你可以訪問在代碼中整個組件和它的所有屬性爲UIComponent對象。你可以用這個組件做很多工作,因爲現在它可以在你的java代碼中使用。 舉個例子,你可以改變它的樣式。

public HtmlInputText getInputText() { 
    inputText.setStyle("color:red"); 
    return inputText; 
} 

或者乾脆根據bean屬性

if(someBoolean) { 
    inputText.setDisabled(true); 
} 

等禁用的組件....

+2

好的,非常感謝您的回覆。換句話說,綁定比獲取價值更強大,因爲你得到整個組件。但是,當在JSF Restore View ...渲染響應週期結合呈現時,與值相比? – csharp

+0

如果我正確理解你的問題,答案是'是'。當你加載你的頁面時,綁定到bean的組件的getters被調用,所以組件被恢復。 – prageeth

相關問題