JSF Custom Tag Tutorial

In this tutorial we will show how to create JSF custom tags based on content defined in an XHTML page.

Creating custom JSF tags can be done either by means of Java classes implementing the UIComponentBase interface or by means of XHTML code fragments. In this tutorial we will show the latter option. Creating a custom JSF XHTML based tag can be quite useful if you want to reuse across your pages some templates such as forms or general settings.
Creating your custom tag requires just three simple steps:

Step # 1 Define your tag content

The following form.xhtml page contains (within an ui:composition section) a block of XHTML code we want to reuse across our pages:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
<html xmlns="http://www.w3.org/1999/xhtml"
                <td>Name:<h:inputText value="#{user.name}" />
                <td>Surname:<h:inputText value="#{user.surname}" /></td>
                <h:commandButton type="submit" action="#{user.action}" value="#{buttonLabel}" />  


Please notice that this template XHTML page is using EL expressions both for referencing Managed Beans (The User Bean) and for custom values which can be added to the tags (The #{buttonLabel) expression which will be used in the tag to customize its look)

Save this page somewhere under the WEB-INF folder so that it can be found by the Web classloader. In our example we have saved it as WEB_INF/tags/form.xhtml

Step #2 Define your tag within a tag lib file:

Add the following custom.taglib.xml to your WEB-INF folder:

<facelet-taglib xmlns="http://java.sun.com/xml/ns/javaee"


As you can see, we are referencing the source XHTML contained in tags/form.xhtml and associating it with the “form” tag name.

Step #3 Add a reference to your tag lib in web.xml



(Please note that the older facelets.LIBRARIES property has been deprecated and might not work in some Java EE servers. So use the above javax.faces.FACELETS_LIBRARIES for JSF 2 compliant servers)

Now that everything is in place you can just reference your tag within your XHTML pages as shown:

<html xmlns="http://www.w3.org/1999/xhtml"


    <ct:form buttonLabel="ClickMe" />


In this tutorial, you’ve learned the essential steps for creating a JSF custom tag. You explored how to define the tag attributes, its behavior using the UIComponent class, and how to render the custom component using JSP or Facelets templates. By following these steps and understanding the core concepts, you can create reusable components that enhance the functionality and maintainability of your JSF applications.