只要在我的 .xhtml 中包含一个封装了 commandButton 的组合,无论使用哪个 commandButton,都会重新初始化 viewscoped bean。我的合成错了吗?请让我知道,因为我真的很想为我的按钮使用复合材料。
简单的测试用例:
@ManagedBean
@ViewScoped
public class Test implements Serializable {
private static final long serialVersionUID = 123456L;
private static int i = 0;
private int counter;
private String table;
private transient DataModel<String> model;
@PostConstruct
public void test() {
System.out.println(".......... PostConstruct");
i++;
List<String> modelData = new ArrayList<String>();
modelData.add("hello");
modelData.add("world");
model = new ListDataModel<String>(modelData);
}
public int getCounter() {
return counter;
}
public String getTable() {
return table;
}
public DataModel<String> getModel() {
return model;
}
public void tableListener() {
String data = model.getRowData();
table = data.toUpperCase();
}
}
无论单击哪个按钮(第 2 列或第 3 列),都会一遍又一遍地调用 postConstruct 方法
<h:form>
<h:dataTable style="width: 40em" var="line" value="#{test.model}">
<h:column>
<f:facet name="header">string</f:facet>
#{line}
</h:column>
<h:column>
<f:facet name="header">actie...1</f:facet>
<h:commandButton value="toUpper" immediate="true" >
<f:ajax event="click" execute="@form" render=":testTable" listener="#{test.tableListener}" />
</h:commandButton>
</h:column>
<h:column>
<f:facet name="header">actie...2</f:facet>
<cmp:rowAction managedBean="#{test}" label="button" listener="tableListener"
tooltip="test via composite" img="stop.png" render=":testTable"/>
</h:column>
</h:dataTable>
</h:form>
一旦最后一列(标题actie...2)被删除,那么@PostConstruct 只被调用一次,正如预期的那样。
为什么我的复合力的存在会重新初始化 viewscoped bean?我的复合有什么问题,它可以工作,但它不应该重新初始化托管 bean:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:cc="http://java.sun.com/jsf/composite"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<!-- INTERFACE -->
<cc:interface>
<cc:attribute name="label" required="true"/>
<cc:attribute name="render"/>
<cc:attribute name="tooltip"/>
<cc:attribute name="img"/>
<cc:attribute name="listener" required="true"/>
<cc:attribute name="managedBean" required="true"/>
</cc:interface>
<!-- IMPLEMENTATION -->
<cc:implementation>
<h:commandButton id="btn_#{cc.attrs.label}" title="#{cc.attrs.tooltip}" immediate="true"
image="/resources/img/#{cc.attrs.img}">
<f:ajax event="click" execute="@form" render="#{cc.attrs.render}" listener="#{cc.attrs.managedBean[cc.attrs.listener]}" />
</h:commandButton>
</cc:implementation>