jsf - 值和绑定(bind)之间的区别

标签 jsf

使用 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/

相关文章:

jsf - FacesContext.getCurrentInstance()在Runnable类中返回null

eclipse for java-如何将对 jsf 2.1 的支持添加到 eclipse 3.7-indigo

java - 如何在 JSF 中与 (MySQL) 数据库交互

java - JSF、AJAX、使用 selectOneMenu 更新动态表

jsf - PrimeFaces fileUpload显示上传后的文件名

JSF:使用 ViewScoped 实现书签功能

java - JSF ConvertDateTime 呈现前一天

java - :message not displayed in jsf page

jsf - pageflowScope 在 ADF Faces 中到底有什么作用?

jsf - 持久化由 JSF 组件转换器创建的 EJB 实体时如何避免重复的 DB 内容?