我在页面上使用数据表并使用绑定属性将其绑定到我的支持 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:h="http://java.sun.com/jsf/html"
      xmlns:p="http://primefaces.prime.com.tr/ui">
    <h:head>
        <title>Facelet Title</title>
    </h:head>
    <h:body>
            <h:form prependId="false">
                <h:dataTable var="item" value="#{testBean.stringCollection}" binding="#{testBean.dataTable}">
                    <h:column>
                        <h:outputText value="#{item}"/>
                    </h:column>
                    <h:column>
                        <h:commandButton value="Click" actionListener="#{testBean.action}"/>
                    </h:column>
                </h:dataTable>
            </h:form>
    </h:body>
</html>
这是我的豆子:-
package managedBeans;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.component.html.HtmlDataTable;
@ManagedBean(name="testBean")
@ViewScoped
public class testBean implements Serializable {
    private List<String> stringCollection;
    public List<String> getStringCollection() {
        return stringCollection;
    }
    public void setStringCollection(List<String> stringCollection) {
        this.stringCollection = stringCollection;
    }
    private HtmlDataTable dataTable;
    public HtmlDataTable getDataTable() {
        return dataTable;
    }
    public void setDataTable(HtmlDataTable dataTable) {
        this.dataTable = dataTable;
    }
    @PostConstruct
    public void init(){
        System.out.println("Post Construct fired!!");
        stringCollection = new ArrayList<String>();
        stringCollection.add("a");
        stringCollection.add("b");
        stringCollection.add("c");
    }
    public void action(){
        System.out.println("Clicked!!");
    }
}
请告诉我为什么每次单击按钮时@PostConstruct 都会触发?只要我在同一页面上,它就应该只触发一次,因为我的 bean 是@ViewScoped。此外,如果我删除绑定属性,那么一切正常,@PostConstruct 回调只触发一次。那为什么每次我使用绑定属性时?我需要绑定属性,并且只想执行一次初始化任务,例如从 web 服务获取数据等。我应该怎么办?我应该在哪里写我的初始化任务?