Tuesday, April 23, 2013

Writing Custom components for JSF-2.0

With the introduction of JSF-2 along came some feature which were simplified. One such feature is creation of custom JSF components.

Why is it required?

Well one reason for it is that is wrapping up the tag which is complex in itself. To make it more simple to use and user-friendly.

Consider a simple case:
I need to have a marquee component, in which I will just mention the string which will be floated in my HTML and the rest will be done component renderer itself.

How is it done?

So first of all in order to make this work, we need to understand what all files we need to create or update.

(MarqueeComponent.java) First of all we need to extend "javax.faces.component.UIComponentBase", extending this class gives us the methods which are used to translate a tag into its HTML equivalent. Look at the annotation @FacesComponent, using this we declare the component type, which is then used in faces-config.xml for declaring the component.

(faces-config.xml) After extending UIComponentBase class, it was required to communicate to JSF that a custom component is created the configuration for the same is mentioned below in the code snippets.

NOTE: You need to configure component in faces-config.xml, iff @FacesComponent is not being used to register the component. @FacesComponent and <component> tag in faces-config.xml are alternatives of each other. @henk, Thanks for pointing out.

(marquee-taglib.xml) And the next part is to create a taglib for the same so that we can use the tags JSF files. As once taglibs are loaded in web-application then only we can use those tags.

(web.xml - snippet) But still one part is missing, we still haven't mentioned the part where we are supposed to load the taglibs in the web-application. For the same, we need to mention the taglib file in web.xml, under context param javax.faces.FACELETS_LIBRARIES 

(sample.xhtml) A sample to demonstrate the custom tag.



  1. If you need supporting tools, JSF Components Wizard is for you, check out http://jcw.jsfportal.org

  2. This comment has been removed by the author.

  3. This comment has been removed by the author.

  4. This comment has been removed by the author.

  5. no librarry found for name space "http://bla.blaa.." i got this error at facelets page.

  6. Thanks for tutorial.

    Can anyone give me example for user define widget using JSF.

    Thanks in advance.

  7. I tried your tutorial but in my case, setValue method is never called. So value is always null.
    What is wrong ?