0

我有下一个问题!

我想从我的支持 bean 动态创建 inputtext,它们将在一个选项卡内,也是动态创建的,它将在执行时构建。

我设法使用input相应的类动态添加组件。

但是我还没有设法将值标签添加到组件中,这是valueExpresion一种将值绑定到managedBean自身的语言。

我找到了一些可以像这样总结的代码。

  @ManagedBean
  @ViewScoped
  public MyManagedBean(){

private TabView tabsi;
    HtmlOutputLabel hol = new HtmlOutputLabel();
        InputText txt2 = new InputText();
private String value;

/* getter and setters */

    public void MyManagedBean{
    tabsi = new TabView();
            Tab tab1 = new Tab();
            tab1.setTitle("Tab1");
            Tab tab2 = new Tab();
            tab2.setTitle("Tab2");
            tabsi.getChildren().add(tab1);
            tabsi.getChildren().add(tab2);

            hol.setValue("label");
            hol.setStyleClass("label");
            txt2.setValueExpression("value",
                    TestController.getExpression("#{myManagedBean.value}"));
            txt2.setValue(value);
            tab1.getChildren().add(hol);
            tab1.getChildren().add(txt2);
    }

    public static ValueExpression getExpression(String expression) {
            FacesContext fc = FacesContext.getCurrentInstance();
            ELContext ctx = fc.getELContext();
            ExpressionFactory factory = fc.getApplication().getExpressionFactory();
            return factory.createValueExpression(ctx, expression, Object.class);
        }

public void test1() {
        System.out.println(value);
    }
    }

我成功地构建了组件,但我无法绑定它来设置ValueExpression. 当我从按钮调用 test1 函数时,它会打印null

如何将值绑定到ManagedBean???

4

1 回答 1

0

我无法用目前提供的信息确定确切原因,但这种方法至少存在三个严重问题:

  1. 实例UIComponent本质上是请求范围的。你永远不应该在更广泛的范围内将它声明为 bean 的属性,否则当在多个视图中引用同一个实例时,你将面临臭名昭著的“重复组件 ID”错误。

  2. 使用binding引用视图范围 bean 属性的属性会完全破坏视图范围。每次请求都会重新创建 bean。这个问题基本上与这里详细解释的理由相同:JSTL in JSF2 Facelets... 有意义吗?

  3. A programmatically created UIInput and UICommand component must have a fixed id set via setId(), otherwise JSF won't be able to find it in the request parameter map during apply request values phase of the form submit and inherently not be able to process the submitted value and the action method respectively.

The third problem is most likely the exact cause of your current problem, but the first and the second problem may have had some influence.

Regardless of this, try to reconsider your decision to programmatically create components this way. This should be avoided as much as possible. E.g. why don't you just use rendered attribute, or view build time tags like JSTL <c:if>?

于 2013-03-13T13:01:55.780 回答