3/11/2011

New Features of JSF 2.0 - Part 2

One thing that was annoying for me since I started working with JSF / ICEFaces was that it is really hard to write reusable components. Especially for firms writing a lot of ICEFaces portlets or applications such a mechanism would save a lot of money.


But, thanks to JSF 2.0, those reusable components will be possible.


JSF 2.0 : Custom Components - Part 1


Custom Components allow you to create truly reusable components in JSF. Those components are that reusable that they will work with any kind of bean you put into them. This means that you can use your components in different projects with different beans.


How to create your first "Hello World" Custom Component


First decide for a namespace. In our case we will use "helloWorld". In this namespace we will create our first component : the testComponent. Create an empty xhtml file. Because all custom components are placed in the standard JSF 2.0 resources folder, we will now have the following structure:

\resources\helloWorld\testComponent.xhtml

We will now create the content for our component. The first component we create will do nothing but to print out "Hello World":


<!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:h="http://java.sun.com/jsf/html"
         xmlns:composite="http://java.sun.com/jsf/composite">
   <h:head>
<title>Hello World</title>
   </h:head>


   <h:body>
   <composite:interface>
   </composite:interface>


   <composite:implementation>
   <h1>Hello World</h1>
   </composite:implementation>


   </h:body>
   </html>


The component is created, now we will use it. Create a file called "index.xhtml" and configure it to use our first component. Therefore you import the namespace we just created, prefixed by "http://java.sun.com/jsf/composite/":


<!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:h="http://java.sun.com/jsf/html"
 xmlns:f="http://java.sun.com/jsf/core"
         xmlns:ui="http://java.sun.com/jsf/facelets"
       xmlns:test="http://java.sun.com/jsf/composite/helloWorld">
   <h:head>
<title>Hello World Usage</title>
   </h:head>


   <h:body>
     <f:outputText value="I just wanted to say"/>  
     <test:testComponent/>
   </h:body>
</html>


You can use the component simply by adding this to your file: <test:testComponent/>.


The example we created above works, but of course is a little simple. It gets really interesting, when we start passing parameters into our component. This will be done in Part 3.



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.