Dec 19, 2013

JSF Composite Components for reusability

Q. Can you explain what are composite components in JSF?
A. JSF 2.0 introduced reusable components called composite components. It uses "cc" ( Composite Component)as the prefix in .xhtml files.

Q. How will you create a Composite Component in JSF 2.0 or later versions?
A. If you want to write a component say login.xhtml and call it from a page named register.xhtml, here are the basic steps.

Step 1: Define the component under
  • src/main/webapp/resources  in your war file or
  • src/main/resources/META-INF/resources  in you jar file

Let's define the login.xhtml  under src/main/webapp/resources/login-folder

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
<html xmlns=""   
     <composite:attribute name="userNameLabel" />
     <composite:attribute name="userNameValue" />
     <composite:attribute name="passwordLabel" />
     <composite:attribute name="passwordValue" />
  <h:panelGrid columns="2" id="textPanel">
   #{cc.attrs.userNameLabel} : 
   <h:inputText id="name" value="#{cc.attrs.userNameValue}" />
   #{cc.attrs.passwordLabel} : 
   <h:inputText id="password" value="#{cc.attrs.passwordValue}" />

Note: cc.attrs.userNameLabel refers to userNameLabel defined in the composite:interface. "cc.attrs" is an internal JSF prefix. It uses other prefixes like cc:clientId, which returns current composite component's prefix.

Step 2: Invoke the composite component from the register.xhtml page. This is what passes the  values to the components interface.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
<html xmlns=""   
     <h1>Composite Components in JSF 2.0</h1>
 <registration:login id="loginComponent"


The component is registered under the name "registration" prefix --> and "login-folder" tells you where to find the component under src/main/webapp/resources.

The registration:login --> registration is the prefix and login denotes look for login.xhtml under the folder src/main/webapp/resources/login-folder which is defined by the registration name space prefix in the html element.

The #{cc.clientId} value will be "loginComponent"

Step 3: #{} refers to the JSF managed bean class. Where "user" is the annotated value and name is a Java class instance variable.

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
public class UserBean{
 public String name;
 public String password;
 //getter and setter methods for name and password
 //any action class methods

Search for "JSF" or click on the JSF cloud tag for more blog posts on JSF with diagrams and code snippets. JSF is kind of in a decline in favor of JavaScript based frameworks like angular-js. I have a few posts on angularjs and Javascript .  JSF mainly used for enhancing or maintaining existing applications.



Post a Comment

Subscribe to Post Comments [Atom]

<< Home