Search code examples
jsfjsf-2managed-bean

Can I use multiple managed bean in the same xhtml page?


when there are data that are repeated in several pages (reference example) Is that I can load into a single managed bean and I use several managed bean in the same page. What is its impact?


Solution

  • Can I use multiple managed bean in the same xhtml page?

    Yes, you can, I highly recommend you to try it :).

    What is its impact?

    This depends on the managed beans scopes. A good example is having a view to register a new address and shows the logged user info at the top of the page, similar to Amazon site where you add a new shipping address.

    In this case, you can have among three managed beans:

    • A @SessionScoped bean that will show the logged user info. In case of amazon view, it shows only the first name.
    • A @ApplicationScoped bean that will provide the data for Countries. This info doesn't change too often (at least that a new country is born every day =\).
    • A @ViewScoped bean that will handle the request data, error messages and the registration.

    A sample of the above explanation in Facelets code:

    <div id="top">
        Hello #{sessionBean.user.firstName}
    </div>
    <div id="body">
        <h1>Add an address</h1>
        <h:form id="frmAddress">
            <h:panelGrid columns="2">
                <h:outputText value="Address" />
                <h:inputText id="txtAddress" value="#{viewBean.address}" />
                <h:outputText value="Country" />
                <h:selectOneMenu id="ddlCountry" value="#{viewBean.selectedCountry}">
                    <f:selectItems value="#{applicationBean.countries}" var="country"
                        itemLabel="#{country.name}" itemValue="#{country}" />
                </h:selectOneMenu>
            </h:panelGrid>
            <h:messages id="msgErrors" />
            <h:commandButton value="Save address" action="#{viewBean.saveAddress}" />
        </h:form>
    </div>
    

    Note: this is nor a good nor a bad practice, just give it a try to see how this behaves. The impact is defined how each managed bean behaves in the page, so it will be pretty neat or a really bad experience, based on how you have defined the beans.

    Related info: