Close

JSF - Creating Custom Component

[Last Updated: Aug 24, 2017]

This example demonstrates how to create a custom JSF component. The component will include the rendering code itself, instead of delegating to a renderer.

The Component

@FacesComponent(createTag = true, tagName = "helloComponent", namespace = "http://example.com/tags")
public class HelloComponent extends UIComponentBase {
    @Override
    public String getFamily() {
        return "Greeting";
    }

    @Override
    public void encodeBegin(FacesContext context) throws IOException {
        String message = (String) getAttributes().get("message");
        LocalDateTime time = (LocalDateTime) getAttributes().get("time");
        String formattedTime = time.format(
                DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM));

        ResponseWriter writer = context.getResponseWriter();
        writer.startElement("p", this);
        writer.write("Message: " + message);
        writer.endElement("p");

        writer.startElement("p", this);
        writer.write("Time: " + formattedTime);
        writer.endElement("p");
    }
}

View

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://example.com/tags">
<h:head></h:head>
<h:body>
    <h2>JSF Custom 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 LocalDateTime getTime() {
        return LocalDateTime.now();
    }
}

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 Custom Component Select All Download
  • custom-component-basic
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • HelloComponent.java
          • webapp

    See Also