Close

PrimeFaces - Lazy Loading and Caching of TabView

[Last Updated: Jul 12, 2017]

This example is the enhancement of the last example. Here, we will learn how to build a tabView which will load the tabs on demand, i.e. a tab will be loaded via an ajax call when it is shown for the first time. To achieve that we have to specify dynamic="true" attribute of the tabView tag. Also, in our example, the data will be cached for the further access of the same tab (instead of loading via ajax call every time). For that we have to specify cache="true" attribute of the tabView tag.

JSF page

src/main/webapp/index.xhtml

<h:body>
    <h2>PrimeFaces TabView Example</h2>
    <p:tabView dynamic="true" cache="true">
        <c:forEach items="#{tabBean.tabs}" var="tabInfo" varStatus="vs">
            <p:tab title="#{tabInfo.title}">
                <h:outputText value = "Loaded at: #{tabBean.timeNow}"/>
                <ui:include src="#{tabInfo.page}.xhtml"/>
            </p:tab>
        </c:forEach>
    </p:tabView>
</h:body>

The manage bean

@ManagedBean
@ViewScoped
public class TabBean {
  private List<TabInfo> tabs;

  @PostConstruct
  public void init() {
      tabs = Arrays.asList(new TabInfo("About", "about"),
              new TabInfo("Reviews", "reviews"),
              new TabInfo("Contact Us", "contact-us")
      );
  }

  public List<TabInfo> getTabs() {
      return tabs;
  }

  public String getTimeNow() {
      return LocalTime.now().toString();
  }
}
public class TabInfo {
  private final String title;
  private final String page;
    .............
}

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war

Output

"Loaded at" time will be updated only once when accessing a tab for the first time.

Example Project

Dependencies and Technologies Used:

  • primefaces 6.1 primefaces
  • jsf-api 2.2.14: This is the master POM file for Oracle's Implementation of the JSF 2.2 Specification.
  • jsf-impl 2.2.14: This is the master POM file for Oracle's Implementation of the JSF 2.2 Specification.
  • jstl 1.2 javax.servlet:jstl
  • JDK 1.8
  • Maven 3.3.9

Lazy and Cached TabView Example Project Select All Download
  • tab-view-lazy-and-cached
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • webapp
          • index.xhtml

    See Also