Tutorial: Creating your own reusable JSF Component (JSF 1.2)

Creating your Own Component

Ok, here is a little tutorial on how to create a reusable component in JSF that you can use with various beans. Not quite as comfortable as with JSF 2.0 but you can almost get the same results.

1) Create a Reference for the taglib

Add the following to your web.xml:

Now your taglib can be accessed in your application

2) Give the taglib some content to reference your files

Here is an examle entry in the taglib (/ui/templates/taglib.xm) that shows to a component: 
<?xml version="1.0"?>
<!DOCTYPE facelet-taglib PUBLIC
  "-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN"

If you want to access your component , you can do that by using the namespace  (some.namespace.com) and the tag name (beanComponent).

3) Call your component 

For the call within a facelets file, add the namespace to the list of references name spaces in the header. 
This is a lot easier in JSF 2.0 ... well , anyway. You can access your component now:
<some:beanComponent bean=${backingbean}/>

In this example we pass the backing bean into the reusable component by using a jstl expression. Don´t try to use the JSF standard like #{backingbean}.

4) The component

The component first has the usual header definitions, starts a ui:composition, and then accesses the bean:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns="http://www.w3.org/1999/xhtml"
<h:outputText value="#{backingBean.wert}"/>

You can access the bean (as always) by using #{backingBean.wert}. This allows you to use your component with different beans.
5) Extension
If you want to make your component even more flexible and dynamic, you can also pass thenames of methods into your component and access them dynamically. You can do so by creating your component like this:
<some:beanComponent bean=${backingbean} method="wert"/>
... and access it like that:
<h:outputText value="#{backingBean[method]}"/>

You can´t get any more flexible ;)

If you like this tutorial it would be very nice, if you could click on some of the google ads you see on the right side. It helps me run this block and motivates me ;)

If you have any questions, feel free to leave a comment.