<h:dataTable value=#{myBean.xxx}>: getXxx() get called so many times, why?

隐身守侯 提交于 2019-12-18 18:10:23

问题


Simple piece of code about dataTable. CentralFeed is SessionScoped Bean, and PostComment is RequestScoped Bean

<h:form id="table">
    <h:dataTable value="#{CentralFeed.profileComments}" var="item">
        <h:column>
            <h:outputText value="#{item.comment}"/><br/>
            <h:inputTextarea value="#{item.newComment}" rows="2"/><br/>
            <h:commandButton value="Post" action="#{PostComment.postReply(item)}" />
        </h:column>
    </h:dataTable>
</h:form>

inside CentralFeed.java

private List<NewsFeed> profileComments = null;

public List<NewsFeed> getProfileComments() {
    PhaseId currentPhaseId = FacesContext.getCurrentInstance().getCurrentPhaseId();
    profileComments = scholarBean.findProfileCommentsByUserId(getSelectedUser().getId());
    //model = new ListDataModel<NewsFeed>(profileComments);
    return profileComments;
}

My problem is that getProfileComments() get called a lot. currentPhaseId will tell us at what phase does the method got called. When the page first load, getProfileComment get call around 5 times, at phase 6 - RENDER_RESPONSE. The page have a inputTextarea, so I type in there something, and click Post (the commandButton). Then getProfileComment get called another 12 times going through phase 1->4. Each phase call this method 3-4 times. Then after that, the setter method of the attribute newComment get call (so setNewComment() get call), the getProfileComment get call again at phase 5. Then postReply() get call, then getProfileComment get call again for another 5 times at phase 6. What is going on? Is it suppose to be like this? If you look at my getProfileComment, via my EJB scholarBean, I actually query the database, so having to query the database like 20 times like this is a very bad idea.


回答1:


Yes, getters can be called multiple times during a request. It doesn't harm as long as it does its sole job properly: returning the bean property. However, in your example you're loading the list straight in the getter method! This should be avoided. Initializing/loading of the model should go in bean's constructor or @PostConstruct or any event based methods like the action method. They get called only once. The getters should only return model data and nothing more (apart from some trivial logging or lazy loading).

See also:

  • Why does JSF call getters multiple times?


来源:https://stackoverflow.com/questions/3973198/hdatatable-value-mybean-xxx-getxxx-get-called-so-many-times-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!