繁体   English   中英

对于以编程方式创建的UI元素,未执行JSF 2.0支持bean方法

[英]JSF 2.0 backing bean method not executed for programmatically created UI element

我正在使用JSF的java类为简单的HTML页面创建UI元素,如下所示。 但是,不会执行Bean :: save()和Item.setValue(...)方法。

item.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;
    }
}

Item.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; }
}

所有以编程方式创建的JSF UIFormUIInputUICommand组件都需要设置固定的ID,否则JSF会自动生成一个不会保存的ID,然后JSF将无法根据请求参数中的ID提取提交的值。地图。

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

editForm.setId("form");
// ...
value.setId("value");
// ...
save.setId("save");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM