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"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facelettaglibrary_2_0.xsd"


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" />

And here’s your custom tag in action:

jsf custom tag tutorial

Download the code from this article.

Found the article helpful? if so please follow us on Socials