12/09/2010

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:

<context-param>
<param-name>facelets.LIBRARIES</param-name>
<param-value>/ui/templates/taglib.xml</param-value>
</context-param>
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"
  "facelet-taglib_1_0.dtd">
<facelet-taglib>
<namespace>http://some.namespace.com</namespace>
<tag>
<tag-name>beanComponent</tag-name>
<source>beanComponent.xhtml</source>
</tag>
</facelet-taglib>

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. 
xmlns:some="http://some.namespace.com"
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"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:z="http://www.qualcomm.com/jsf/core"
xmlns:c="http://java.sun.com/jstl/core"
xmlns:fn="http://java.sun.com/jsp/jstl/functions">
<ui:composition>
<h:outputText value="#{backingBean.wert}"/>
</ui:composition>
</html>


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.