Close

JSF - Creating Composite Component

[Last Updated: Sep 1, 2017]

A JSF composite component is a special type of template that allows to write reusable JSF UI components without any Java code.

A composite component resides in an xhtml file which is placed under 'webapp/resources/myLib/' directory. This file contains two main elements interface and implementation.

Let's see an example to learn how to create a composite JSF component.

Creating a Composite Component

src/main/webapp/resources/example/helloComponent.xhtml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:cc="http://xmlns.jcp.org/jsf/composite">
<h:head></h:head>
<h:body>

    <cc:interface>
        <cc:attribute name="message"/>
        <cc:attribute name="time"/>
    </cc:interface>

    <cc:implementation>
        <h:panelGrid columns="2">
            <h:outputLabel for="msg" value="Message: " />
            <h:outputLabel id="msg" value="#{cc.attrs.message}" />
            <h:outputLabel for="time" value="Time: " />
            <h:outputLabel id="time" value="#{cc.attrs.time}" />
        </h:panelGrid>
   </cc:implementation>

</h:body>
</html>

Using Composite Component

src/main/webapp/index.xhtml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:t="http://xmlns.jcp.org/jsf/composite/example">
<h:head></h:head>
<h:body>
    <h2>JSF Composite Component example</h2>
    <t:helloComponent message="#{helloBean.message}" time="#{helloBean.time}"/>
</h:body>
</html>

Managed Bean

@ManagedBean
@RequestScoped
public class HelloBean {

  public String getMessage() {
      return "Hi there!";
  }

  public String getTime() {
      return LocalDateTime.now().format(
              DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM));
  }
}

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

mvn tomcat7:run-war

Output

Example Project

Dependencies and Technologies Used:

  • 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.
  • JDK 1.8
  • Maven 3.3.9

JSF Composite Component Select All Download
  • composite-component-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • webapp
          • resources
            • example
              • helloComponent.xhtml

    See Also