以下に示すように、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;
}
}
アイテム.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; }
}