使用 JavaServer Faces 的 value 和 binding 有什么区别,什么时候使用一个而不是另一个?为了更清楚我的问题是什么,这里给出了几个简单的例子。
通常在 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";
}
}
但是,当使用“绑定(bind)”时,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>
而对应的 bean 被称为 backing 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";
}
}
这两个系统之间有什么实际区别,什么时候使用 backing bean 而不是常规 bean?可以同时使用吗?
我对此感到困惑已有一段时间了,如果能解决这个问题,我将不胜感激。
最佳答案
value
属性表示组件值 .它是 文字 当您在浏览器中打开页面时,您在文本框中看到的内容。binding
属性用于绑定(bind)你的组件 到 bean 属性。对于您的代码中的示例,您的 inputText
组件像这样绑定(bind)到bean。
#{backing_hello.inputText}`
这意味着您可以访问整体组件及其所有属性在您的代码中作为
UIComponent
目的。您可以对组件进行大量工作,因为现在它可以在您的 java 代码中使用。例如,您可以像这样更改其样式。
public HtmlInputText getInputText() {
inputText.setStyle("color:red");
return inputText;
}
或者只是根据 bean 属性禁用组件
if(someBoolean) {
inputText.setDisabled(true);
}
等等....
关于jsf - 值和绑定(bind)之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13681697/