开发者

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

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>(profil开发者_开发技巧eComments);
    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.


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?
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜