价值与约束力的区别

csh*_*arp 25 jsf

使用值和JavaServer Faces绑定有什么区别,什么时候使用一个而不是另一个?为了更清楚我的问题,这里给出了几个简单的例子.

通常使用XHTML代码中的JSF,您可以使用"value",如下所示:

<h:form> 
  <h:inputText value="#{hello.inputText}"/>
  <h:commandButton value="Click Me!" action="#{hello.action}"/>
  <h:outputText value="#{hello.outputText}"/>
</h:form>
Run Code Online (Sandbox Code Playgroud)

然后豆子是:

// 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";
}
}
Run Code Online (Sandbox Code Playgroud)

但是,使用"绑定"时,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>
Run Code Online (Sandbox Code Playgroud)

对应的bean被称为支持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";
}
}
Run Code Online (Sandbox Code Playgroud)

两个系统之间存在哪些实际差异,何时使用支持bean而不是常规bean?可以同时使用两者吗?

一段时间以来,我一直对此感到困惑,并且非常感谢清理它.

pra*_*eth 42

valueattribute表示组件.它是文本您在文本框内看到当你在浏览器中打开页面.

bindingattribute用于将组件绑定到bean属性.对于代码中的示例,您的inputText组件就像这样绑定到bean.

#{backing_hello.inputText}`
Run Code Online (Sandbox Code Playgroud)

这意味着您可以将代码中的整个组件及其所有属性作为UIComponent对象进行访问.您可以使用该组件进行大量工作,因为现在它可以在您的Java代码中使用.例如,您可以像这样更改其样式.

public HtmlInputText getInputText() {
    inputText.setStyle("color:red");
    return inputText;
}
Run Code Online (Sandbox Code Playgroud)

或者只是根据bean属性禁用组件

if(someBoolean) {
  inputText.setDisabled(true);
}
Run Code Online (Sandbox Code Playgroud)

等等....

  • 好的,非常感谢您的回复.换句话说,绑定比获取整个组件要强大得多.但是,在JSF Restore View中....渲染响应周期是绑定渲染,与值相比? (2认同)

San*_*nda 3

有时我们并不真正需要将 UIComponent 的值应用到 bean 属性。例如,您可能需要访问 UIComponent 并使用它,而不将其值应用于模型属性。在这种情况下,最好使用辅助 bean 而不是普通 bean。另一方面,在某些情况下,我们可能需要使用 UIComponent 的值,而不需要以编程方式访问它们。在这种情况下,你可以选择普通的豆子。

因此,规则是仅当您需要以编程方式访问视图中声明的组件时才使用支持 bean。在其他情况下使用普通豆子。