Ajax menu navigation in JSF with OpenFaces

Problem: Webpage must change body contents fast without reloading whole page when user clicks link in menu.

Solution: It can be achieved using OpenFaces o:layeredPane component.

In menu can be used commandLinks surrounded with form. Commandlinks include f:param which sends to server what contents must be displayed. When clicking link then browser sends ajax request to server and bean action method is performed.

        <h:form>
            <h:panelGrid columns="1">
                <h:commandLink value="#{msgs.frontpagelink}" action="#{frontPageBean.changeBody}">
                    <f:param name="pageViewId" value="0"/>
                    <f:ajax render=":fbody"></f:ajax>
                </h:commandLink>
                <h:commandLink value="#{msgs.contactlink}" action="#{frontPageBean.changeBody}">
                    <f:param name="pageViewId" value="1"/>
                    <f:ajax render=":fbody"></f:ajax>
                </h:commandLink>
            </h:panelGrid>
        </h:form>

Bean contains following method that extracts request parameter and assigns it to bean parameter.

public String changeBody() { FacesContext fc = FacesContext.getCurrentInstance(); String includedPage = fc.getExternalContext().getRequestParameterMap().get("pageViewId"); setFrontpageBody(includedPage); return null; }

In body part is OpenFaces o:layeredPane where are defined all possible o:subPanels

        <ui:define name="body">
              <o:layeredPane id="fbody"
                           selectedIndex="#{frontPageBean.frontPageBody}">
                <o:subPanel>
                    <ui:include src="mainpage.xhtml"></ui:include>
                </o:subPanel>
                <o:subPanel>
                    <ui:include src="contact.xhtml"></ui:include>
                </o:subPanel>
            </o:layeredPane>
        </ui:define>

As a conclusion when clicking menu link then request parameter with page index is sent to server with ajax. Server updates correct page index and when rerendering o:layeredPane then correct page is included into webpage contents.


Leave a Reply

Your email address will not be published.


*