This example demonstrates how to create a custom JSF component. The component will include the rendering code itself, instead of delegating to a renderer.
@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"); } }
<?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>
@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
Dependencies and Technologies Used: