我正在使用 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; }
}