1

我正在使用 JSF 的 java 类为一个简单的 HTML 页面创建 UI 元素,如下所示。然而 Bean::save() 和 Item.setValue(...) 方法并没有被执行。

项目.xhtml

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:h="http://java.sun.com/jsf/html">
    <h:head>
        <title>Test</title>
    </h:head>
    <h:body>
        <h:panelGroup binding="#{bean.htmlPanelGroup}" />
    </h:body>
</html>

Bean.java

@ManagedBean(name="bean")
@ViewScoped
public class Bean implements Serializable {
    private final Item item = new Item(1L, "hello");

    public void save() {
        // this method is not executed when the save button created below is clicked.
        System.out.println("item.value = " + item.getValue());
    }

    public Item getItem() { return this.item; }

    transient HtmlPanelGroup htmlPanelGroup;

    public void setHtmlPanelGroup(HtmlPanelGroup htmlPanelGroup) {
        this.htmlPanelGroup = htmlPanelGroup;
    }
    public HtmlPanelGroup getHtmlPanelGroup() {
        if (htmlPanelGroup == null) {
            FacesContext facesContext = FacesContext.getCurrentInstance();
            htmlPanelGroup = new HtmlPanelGroup();
            HtmlForm editForm = new HtmlForm();
            HtmlInputText value = new HtmlInputText();
            ValueExpression valueExpr = facesContext.getApplication().getExpressionFactory()
            .createValueExpression(facesContext.getELContext(), "#{bean.item.value}", String.class);
            value.setValueExpression("value", valueExpr);
            editForm.getChildren().add(value);
            HtmlCommandButton save = new HtmlCommandButton();
            save.setValue("save");
            MethodExpression methodExpr = facesContext.getApplication().getExpressionFactory()
            .createMethodExpression(facesContext.getELContext(), "#{bean.save}", String.class, new Class<?>[]{});
            save.setActionExpression(methodExpr);
            editForm.getChildren().add(save);
            htmlPanelGroup.getChildren().add(editForm);
        }
        return htmlPanelGroup;
    }
}

项目.java

public class Item implements Serializable {
    private long id;
    private String value;

    public Item(long id, String value) {
        this.id = id;
        this.value = value;
    }

    public String getValue() { return value; }

    public void setValue(String value) { this.value = value; }

    public long getId() { return id; }

    public void setId(long id) { this.id = id; }
}
4

1 回答 1

1

所有以编程方式创建的 JSFUIForm和组件都需要有一个固定的 ID 集,否则 JSF 会自动生成一个不会保存的 ID,然后 JSF 将无法根据请求参数映射中的这些 ID 提取提交的值UIInputUICommand

因此,在您的特定情况下,您需要添加以下行(ID 完全由您选择):

editForm.setId("form");
// ...
value.setId("value");
// ...
save.setId("save");
于 2012-07-09T15:04:53.640 回答