Saturday, April 18, 2009

Facelets Tutorial : UI Component Tag-3

<< Previous        Next >>


UI Component Tag - Part 3

Create a JSF Facelets Page

Right-mouse click on the WebContent folder of JSFFaceletsExample application, select New->HTML Page to launch the HTML Page wizard. Type the file name sideMenu.xhtml and click 'Next'. In the Select Templates page of the wizard, select the 'New Facelet Composition Page'. Click 'Finish'. The page will be opened in the Web Page Editor.


The <ui:component> tag can be included into  sideMenu.xhtml just like <ui:composition> tag: Inside the <ui:component> tag we are including a <c:forEach> tag. The c:forEach tag in the core JSTL library is  most useful whenever it is necessary to iterate over data. The example below shows a simple usage of the c:forEach tag which acquires it's data from a bean called menuBackingBean wraps a collection of MenuItem objects. The c:forEach iterates over the MenuItems producing one row for each MenuItem  Each MenuItem has a url, and label properties.

See the full sideMenu.xhtml below:


<!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:c="http://java.sun.com/jstl/core">
   This text will not be rendered.
<ui:component>
      <c:forEach var="menu" items="#{menuBackingBean.menus}">
           <a href="#{menu.url}">#{menu.label}</a><br/>
      </c:forEach>
</ui:component>
</html>


Now we can include sideMenu.xhtml in our main page home.xhtml as follows.

<!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">
<ui:composition template="WEB-INF/templates/insertTemplate.xhtml">
<ui:define name="sidemenu">
        <ui:include src="sideMenu.xhtml" />
</ui:define>
<ui:define name="content">
        This is an example of a simple Facelets template.<br/>
        Here Header and Footer appears from template.(inserTemplate.xhtml)<br/>
        Side Menu appears from sideMenu.xhtml<br/>
        This section appears from templateClient.(home.xhtml)
</ui:define>
</ui:composition>
</html>

Run your webapplication

To run your web application, right click on home.xhtml, click- >run as -> run on server.
Select the server type ,Apache Tomacat v6.0 Server.Click Fininsh.

Open a web browser and type the url : http://localhost:8080/JSFFaceletsExample/home.xhtml

Your page will be rendered like this: