Composite Components in JSF 2.0

Since JSF 2.0, it’s very easy to create a reusable component, known as composite components. In this tutorial, we show you how to create a simple composite components (stored as “register.xhtml“), which is an user registration form, includes name and email text fields (h:inputText) and a submit button (h:commandButton). In addition, we also show you how to use it.

Create a Composite Components

Here’s the steps to create a composite components :

1. Composite Namespace

Create a .xhtml file, and declared the composite namespace.

<html xmlns="http://www.w3.org/1999/xhtml"   
      //...
      xmlns:composite="http://java.sun.com/jsf/composite">
</html>

2. Interface & Implementation

Uses composite tags composite:interface, composite:attribute and composite:implementation, to define content of the composite component. For example,

<html xmlns="http://www.w3.org/1999/xhtml"   
      //...
      xmlns:composite="http://java.sun.com/jsf/composite">
 
	  <composite:interface>
			<composite:attribute name="anything" />
	  </composite:interface>
 
	  <composite:implementation>
			#{cc.attrs.anything}
	  </composite:implementation>
</html>

The composite:interface tag is used to declare the configurable values which are expose to the developer who use it. And composite:implementation tag is declares all the XHTML markups, which are the content of the composite component, inside the composite:implementation tag, you can access composite:interface attribute with the expression #{cc.attrs.attributeName}.

3. Resources Folder

Put composite components (“.xhtml” file) into JSF’s resources folder, see figure 1:

Figure 1 : Directory structure of this example.

jsf2-composite-component-folder

In this case, you put the “register.xhtml” composite components into a folder named “mkyong”.

4. Complete Example

Done, let see a complete example of “register.xhtml”.

File : register.xhtml

<?xml version="1.0" encoding="UTF-8"?>
<!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:composite="http://java.sun.com/jsf/composite"
      >
 
    <composite:interface>
 
    	<composite:attribute name="nameLable" />
    	<composite:attribute name="nameValue" />
    	<composite:attribute name="emailLable" />
    	<composite:attribute name="emailValue" />
 
   	<composite:attribute name="registerButtonText" />
    	<composite:attribute name="registerButtonAction" 
    		method-signature="java.lang.String action()" />
 
    </composite:interface>
 
    <composite:implementation>
 
	<h:form>
 
		<h:message for="textPanel" style="color:red;" />
 
		<h:panelGrid columns="2" id="textPanel">
 
			#{cc.attrs.nameLable} : 
			<h:inputText id="name" value="#{cc.attrs.nameValue}" />
 
			#{cc.attrs.emailLable} : 
			<h:inputText id="email" value="#{cc.attrs.emailValue}" />
 
		</h:panelGrid>
 
		<h:commandButton action="#{cc.attrs.registerButtonAction}" 
			value="#{cc.attrs.registerButtonText}"
		/>
 
	</h:form>
 
    </composite:implementation>
 
</html>

Use a Composite Components

You just created a composite component “register.xhtml”, and now we show you how to use it.

1. Composite Component Access Path

Refer to figure 1 above; the “register.xhtml” file is under the folder “mkyong”. Here’s how you access it :

<html xmlns="http://www.w3.org/1999/xhtml"   
      ///...
      xmlns:mkyong="http://java.sun.com/jsf/composite/mkyong"
      >
	  <mkyong:register />
</html>
http://java.sun.com/jsf/composite/folder-name-in-resources-folder
The folder name of the composite components is defined the component access path, for example, if you put your “register.xhtml” file under folder named “abc”, then you should access it like this :

<html xmlns="http://www.w3.org/1999/xhtml"   
      ///...
      xmlns:mkyong="http://java.sun.com/jsf/composite/abc"
      >
	  <mkyong:register />
</html>

2. Complete Example

Let’s see a complete example to show the use of “register.xhtml” composite components.

File : default.xhtml

<?xml version="1.0" encoding="UTF-8"?>
<!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:mkyong="http://java.sun.com/jsf/composite/mkyong"
      >
 
    <h:body>
 
    	<h1>Composite Components in JSF 2.0</h1>
 
	<mkyong:register 
		nameLable="Name" 
		nameValue="#{user.name}" 
		emailLable="E-mail" 
		emailValue="#{user.email}"
 
		registerButtonText="Register" 
		registerButtonAction="#{user.registerAction}"
	 />
 
    </h:body>
 
</html>

You are allowed to pass either hard-coded value or backing method or property into the composite component via exposed attributes, when the form is submitted, JSF will do all the backing bean binding automatically.

P.S Here’s the “user” managed or backing bean, for those who are interested.

package com.mkyong;
 
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
 
@ManagedBean(name="user")
@SessionScoped
public class UserBean{
 
	public String name;
	public String email;
 
	//getter and setter methods for name and email
 
	public String registerAction(){
		return "result";
	}
}

Demo

Here’s the result.

URL : http://localhost:8080/JavaServerFaces/default.xhtml

jsf2-composite-component-example

Download Source Code

Reference

  1. JSF 2 composite:interface JavaDoc
  2. JSF 2 composite:implementation JavaDoc
  3. JSF 2 composite:attribute JavaDoc
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Pingback: Instagram likes kopen()

  • Pingback: laan penge nu sms()

  • Pingback: stop parking()

  • Pingback: bedste laan lige nu()

  • Pingback: lan her og nu()

  • Pingback: mobile porn movies()

  • Pingback: DirectTV()

  • Pingback: DIRECTV for your company()

  • Pingback: Amazing chick in insatiable gig()

  • Pingback: streaming movies()

  • Pingback: watch tv show episodes()

  • Pingback: Blue Coaster33()

  • Sam

    Hi mkyong,

    thanks for your great article!

    I’m here wondering what’s the advantages and disadvantages for custom tags mentioned in previous section (http://www.mkyong.com/jsf2/custom-tags-in-jsf-2-0/) compared with composite components here. Can you shed the light on it?

    Thanks in advance!

  • Shantanu

    Hi mkyong,
    I depend a lot on your blogs.
    I am currently trying to develop composite components.
    However after doing some basic stuff I was looking for
    the schema for http://java.sun.com/jsf/composite namespace
    and could not get it.
    That would help me in getting IDE tag completion etc.
    Can you send me any pointers regarding the same.

    regards

    • Clement

      For all those whose page has the inclusion of the composite element having the error that “the name space cannot be found”, you MUST create the resources folder under your “Web Pages” folder. It has to be the same level as your WEB-INF folder. All along I had the impression that the “resources” folder was optional; and was specific to certain types of project. I was using the Java Enterprise application which wasn’t so explicit.

      Thank you mkyong too~

  • Saleh

    Thank you for all these tutorials. Many Google searches about Java EE results your website. It is very helpful.

  • Fábio Fagundes

    Great help. Thank you for all off your work.

  • demonz

    hi, great resource. i’m facing a problem with faces.

    launcher.xhtml
     
    this form uses &quot;thing&quot;
     
    &lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;
          xmlns:composite=&quot;http://java.sun.com/jsf/composite&quot;
          xmlns:f=&quot;http://java.sun.com/jsf/core&quot;      
          xmlns:h=&quot;http://java.sun.com/jsf/html&quot;
          xmlns:p=&quot;http://primefaces.org/ui&quot;
          xmlns:ui=&quot;http://java.sun.com/jsf/facelets&quot;
          xmlns:custom=&quot;http://java.sun.com/jsf/composite/components&quot;&gt;
    &lt;h:form id=&quot;form&quot;&gt;
    &lt;p:panelGrid 
    id=&quot;pgid&quot;
    columns=&quot;2&quot;&gt;
        &lt;h:outputText value=&quot;title&quot;/&gt;
        &lt;h:outputText value=&quot;#{bean.value}&quot;/&gt;   
    &lt;/p:panelGrid&gt;
     
    &lt;custom:thing 
    via=&quot;#{bean.via1}&quot;
    viaListener=&quot;#{bean.via2Listener()}&quot;        
    vias=&quot;#{bean.vias1}&quot;&gt;
    &lt;/h:form&gt;
     
    thing.xhtml
     
    &lt;p:selectOneMenu                    
                process=&quot;@this&quot;
                value=&quot;#{cc.attrs.via}&quot;&gt;
                    &lt;p:ajax
                    listener=&quot;#{cc.attrs.viaListener}&quot;
                    update=&quot;form:pgid&quot;
                    /&gt;
                    &lt;f:selectItems value=&quot;#{cc.attrs.vias}&quot;/&gt;
                &lt;/p:selectOneMenu&gt;

    faces can´t find form:pgid. tried with and without prepending “form”. thanks

  • BrightSide

    Hey mkyong, I made use of your tutorial, thank you .

  • Tim

    Hello,

    I also work with composite components, but in combination with other fields and text outside the component.
    What I do is… I put a table on the jsf page that has 2 columns and multiple rows. The first column is a component and the second column contains plain text.
    When you submit the page without ajax and come back to the same page than all components are placed after the text.
    It is as jsf parses first all normal tags, text,… and after that the components.
    Pressing F5 puts everything back normal.

    Someone any idea?

  • Pingback: JSF 2.0 Tutorial()

  • edi

    I works like a charm, now is much much easier to built my own composite components.

    Thank you for the post.

  • Haolin

    I tried the example in both JSF 2.0/Weblogic and Mojarra JSF 2.1.11/Tomcat. But cc.attrs cannot be evaluated. Did you encounter this problem before? Have your code been tested in the environments listed above yet?

  • Pingback: Can I template a h:dataTable? | PHP Developer Resource()

  • Rudra

    Hi Yong, this is very good article,
    can you please give an example to hide if some of the defined fileds in register.xml not required in some jsf pages.

    like my requirement is to hide some fileds in some pages

  • Leandro

    Hello,

    I’m having problem to create the component dynamically.

    What am I doing wrong?

    FacesContext context = FacesContext.getCurrentInstance();
    Resource resource = context.getApplication().getResourceHandler().createResource(“date.xhtml”, “util”);
    DynamicFieldList compositeComponent = (DynamicFieldList)context.getApplication().createComponent(context, resource);
    UIPanel facetComponent = (UIPanel) context.getApplication().createComponent(UIPanel.COMPONENT_TYPE);
    facetComponent.setRendererType(“javax.faces.Group”);
    compositeComponent.getFacets().put(UIComponent.COMPOSITE_FACET_NAME, facetComponent);
    context.getViewRoot().getChildren().add(compositeComponent);

    • Leandro

      No error occurs, the more the component is not displayed

  • naveen

    Hey mk

    I am trying to extend the selectItems tag of core jsf 2.0

    i wrote a class which extends SelectItems and then added an attribute title for tooltip

    i added xml suggested by you (using 1.1 DTD)

    i added context param as per your advice

    still i am getting

    SEVERE: Servlet.service() for servlet [Faces Servlet] in context with path [/app-manager] threw exception [/index.xhtml @22,68  
    Tag Library supports namespace: http://dummy.com/facelets, but no tag was defined for name: selectItems] with root cause
    javax.faces.view.facelets.TagException: /index.xhtml @22,68  
    Tag Library supports namespace: http://dummy.com/facelets, but no tag was defined for name: selectItems
    	at com.sun.faces.facelets.compiler.CompilationManager.pushTag(CompilationManager.java:304)
    	at com.sun.faces.facelets.compiler.SAXCompiler$CompilationHandler.startElement(SAXCompiler.java:255)
    	at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:501)
  • msm

    Hi,

    I have different application structure.
    src
    web
    resources/mykong/register.xhtml
    web-inf

    I have added resource folder in web/resources/mykong/register.xhtml

    1. added name space xmlns:mkyong=”http://java.sun.com/jsf/composite/mkyong” jsf page.

    2.called register in one the jsf page.

    But i am unable to see component?

    Please if anyone has an idea.

  • DE OLIVEIRA

    Hello,

    I create my own component (a panel) :

     

    On my xhtml i use like this

     

    And then when i use the method findComponent with the id “toto”, but this method didn’t find the UIInput with id “toto”.

    If i remove my component around the inputText, the method findComponent find the UIInput.

    Have you got any idea about this problem ?

    Thanks for you help.

    • DE OLIVEIRA

      Sorry for the double post but it seems that the HTML pre markup doesn’t work.

      • http://www.mkyong.com mkyong

        Can’t read your code, try post at javanullpointer.com

        • DE OLIVEIRA

          I’ve sent you another post with the contact form. Hope this will work. Thanks for you help.

          I will try to post on javanullpointer.com too.