Include facelet programatically JSF

The purpose is to use programmatically, then you should be using FaceletContext#includeFacelet() . Assuming that you’re inside your custom component:

FacesContext facesContext = FacesContext.getCurrentInstance();
FaceletContext faceletContext = (FaceletContext) facesContext.getAttributes().get(FaceletContext.FACELET_CONTEXT_KEY);
faceletContext.includeFacelet(this, "include.xhtml"); // this is your current UIComponent.

Here’s another kickoff example which demonstrates dynamic include by command button:

    <h:commandButton value="include" action="#{bean.include}" />
<h:panelGroup id="include" />


public void include() throws IOException {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    FaceletContext faceletContext = (FaceletContext) facesContext.getAttributes().get(FaceletContext.FACELET_CONTEXT_KEY);
    faceletContext.includeFacelet(facesContext.getViewRoot().findComponent("foo"), "include.xhtml");


Include composite component programatically JSF

use FaceletContext#includeFacelet() to include the composite component resource in the given parent.

public static void includeCompositeComponent(UIComponent parent, String libraryName, String resourceName, String id) {
    // Prepare.
    FacesContext context = FacesContext.getCurrentInstance();
    Application application = context.getApplication();
    FaceletContext faceletContext = (FaceletContext) context.getAttributes().get(FaceletContext.FACELET_CONTEXT_KEY);

    // This basically creates <ui:component> based on <composite:interface>.
    Resource resource = application.getResourceHandler().createResource(resourceName, libraryName);
    UIComponent composite = application.createComponent(context, resource);
    composite.setId(id); // Mandatory for the case composite is part of UIForm! Otherwise JSF can't find inputs.

    // This basically creates <composite:implementation>.
    UIComponent implementation = application.createComponent(UIPanel.COMPONENT_TYPE);
    composite.getFacets().put(UIComponent.COMPOSITE_FACET_NAME, implementation);

    // Now include the composite component file in the given parent.
    parent.pushComponentToEL(context, composite); // This makes #{cc} available.
    try {
        faceletContext.includeFacelet(implementation, resource.getURL());
    } catch (IOException e) {
        throw new FacesException(e);
    } finally {

Imagine that you want to include <my:testComposite id="someId"> from URI xmlns:my="", then use it as follows:

includeCompositeComponent(parent, "mycomponents", "testComposite.xhtml", "someId");

This has also been added to JSF utility library OmniFaces as Components#includeCompositeComponent() (since V1.5).

Since JSF 2.2, the ViewDeclarationLanguage class got a new createComponent() method taking the taglib URI and tag name which could also be used for this purpose. So, if you’re using JSF 2.2, the approach should be done as follows:

public static void includeCompositeComponent(UIComponent parent, String taglibURI, String tagName, String id) {
    FacesContext context = FacesContext.getCurrentInstance();
    UIComponent composite = context.getApplication().getViewHandler()
        .getViewDeclarationLanguage(context, context.getViewRoot().getViewId())
        .createComponent(context, taglibURI, tagName, null);

Imagine that you want to include <my:testComposite id="someId"> from URI xmlns:my="", then use it as follows:

includeCompositeComponent(parent, "", "testComposite", "someId");



JSF date/time converters for system’s timezone

JSF date/time converters defaults by specification to UTC timezone. If you want to use a different timezone, then you really need to specify it in the converter yourself. Or, if you have 100% control over the production runtime environment, then set its system timezone to the desired timezone and add the following context parameter to web.xml:


This way JSF will use the system’s timezone as obtained by TimeZone#getDefault() as converter’s default timezone.

Please note that the java.util.Date object by itself also does not store any timezone information. It also always defaults to UTC timezone. Keep this in mind when processing submitted date/times.

Thanks to Ricardo (Metal Apache) Andrade for the link.



JSF 2.2: HTML 5 Support

No doubt HTML 5 is the hottest topic in web development in these years.
Besides a series of new tags are added, the form element support is also improved. The type attribute ofinput element can be textemailnumberrangeurldate etc. Ideally, a browser could provide native validation for these input tags.(but this feature support is very different between browsers).

JSF 2.0

In JSF 2.0, some attributes of HTML 5 form elements can not be rendered correctly in the standard JSF input components. For example, <input type=”email” can not be rendered by <h:inputText type=”email”.
omnifaces fixes the issue, and adds basic HTML5 form elements support by a extenedHtml5RenderKitFactory.
What you need to do is declare a Html5RenderKitFactory in the faces-config.xml.


Now, the <h:inputText type=”email” can be rendered as expected.
But unfortunately, the omnifaces solution does not support custom data- attributes in the HTML 5 form input tags.

HTML5 support in JSF 2.2

In Java EE 7, HTML 5 is the first class citizen. But refactoring all JSF components to add extra input attributes is not a smart decision. JSF 2.2 provided a compromise solution to support HTML 5 input tags.

They are called Passthrough Attributes and Passthrough Elements respectively.

Passthrough Attributes

JSF 2.2 provides a new facelets taglib namespace to process Passthrough Attributes.


For example, you want to add placeholder to input element, just added a p:placeholder attribute.

<h:inputText p:placeholder="Type text here..."/>

This tell JSF HTMLRenderKit keep back the attribute placeholder directly, not like JSF 2.0, any none support attributes will be ate by HTML RenderKit.
The core taglib also added a new tag to support passthrough feature.

<f:passThroughAttribute name="placeholder" value="Type text here..."/>

This is equivalent to the above version.
You can add more than one attributes at the same time.

 <h:inputText id="number" p:type="number" p:min="1" p:max="10"  value="..."/>

Or use multi f:passThroughAttribute nested in the inputText component.

<h:inputText id="text" value="#{html5Bean.text}" required="true">  
    <f:passThroughAttribute name="placeholder" value="Type text here..."/>
    <f:passThroughAttribute name="required" value="true"/>

Or use a f:passThroughAttributes nested in the inputText component, it can accept a Map.

<f:passThroughAttributes value="#{html5Bean.attrs}"/>

In backend bean, a Map is declared.

private Map<String, String> attrs = new HashMap<String, String>();

public void init() {" call init@");
    this.attrs.put("type", "range");
    this.attrs.put("min", "1");
    this.attrs.put("max", "10");
    this.attrs.put("step", "2");

You can also use a EL 3.0 Map expression as value. EL 3.0 is extracted from JSF specifcation as a standalone specification now, we will discuss it in further post.

<f:passThroughAttributes value="#{{'type':'range', 'min':'0', 'max':'10', 'step':'2'}}"/>

A complete example of Passthrough Attributes.

    <h:messages showDetail="false" showSummary="true"/>
    Text: <h:inputText id="text" value="#{html5Bean.text}" required="true">  
        <f:passThroughAttribute name="placeholder" value="Type text here..."/>
        <f:passThroughAttribute name="required" value="true"/>
    Url: <h:inputText id="url" value="#{html5Bean.url}">
        <f:passThroughAttribute name="type" value="url"/>
    Email: <h:inputText id="email" p:type="email" value="#{}" /><br/>
    Number: <h:inputText id="number" p:type="number" p:min="1" p:max="10"  value="#{html5Bean.number}" >
        <f:convertNumber minFractionDigits="0"/>
    </h:inputText> <br/>
    Range: <h:inputText id="range" value="#{html5Bean.range}">
        <!-- f:passThroughAttributes value="#{html5Bean.attrs}"/ -->
        <f:passThroughAttributes value="#{{'type':'range', 'min':'0', 'max':'10', 'step':'2'}}"/>
        <f:convertNumber minFractionDigits="0"/>
    Date: <h:inputText id="date" p:type="date" value="#{}" >
        <f:convertDateTime pattern="yyyy-MM-dd"/>
    <h:commandButton value="Save" action="#{html5Bean.submit()}">
        <f:ajax execute="@form" render="@all"/>

<h:panelGroup id="out">
    Text:  <h:outputText value="#{html5Bean.text}"/><br/>
    Url:  <h:outputText value="#{html5Bean.url}"/><br/>
    Email:  <h:outputText value="#{}"/><br/>
    Number:  <h:outputText value="#{html5Bean.number}"/><br/>
    Range:  <h:outputText value="#{html5Bean.range}"/><br/>
    Date:  <h:outputText value="#{}"/><br/>

Through the passthrough feature in JSF 2.2, you can add any custom attribute to input element, such as the data-XXX attribute in Bootstrap framework.
The Passthrough Attributes way is very friendly when you migrate the existed JSF application to JSF 2.2 and make it compatible with HTML 5.

Passthrough Elements

JSF 2.2 provides another facelets taglib namespace to support Passthrough Elements feature.


All plain HTML element will be treated as equivalent facelets components.
For example.

<input jsf:id="text" type="text" jsf:value="#{html5Bean.text}" required="required" placeholder="Type text here..."/>

is equivalent to the <h:inputText. All standard attributes of h:inputText in the input tag can be treated automatically. The extra placeholder attributes will be keep as it is after it is rendered.
You can find the complete comparison table between plain HTML tags and facelets components fromOracle Java EE tutorial.
As described in the Java EE tutorial, you have to mark at least one of the attributes with jsf prefix as a maker to make the input tag to be processed as a JSF component.
NOTE: In the above example, I found I have to add “jsf:” to the value attribute to make it work, or it will throw an exception at runtime, even I added a jsf:id in the the input tag already.
It is simple and stupid, and it is very friendly when you work together with a web designer.
An complete example to demonstrate Passthrough Elements feature.

<h:form prependId="false">
    <h:messages showDetail="false" showSummary="true"/>
    Text: <input jsf:id="text" type="text" jsf:value="#{html5Bean.text}" required="required" placeholder="Type text here..."/>  
    Url: <input jsf:id="url" type="url"  jsf:value="#{html5Bean.url}"/><br/>

    Email: <input type="email" jsf:id="email" jsf:value="#{}" /><br/>
    Number: <input jsf:id="number" type="number" min="1" max="10"  jsf:value="#{html5Bean.number}" >
        <f:convertNumber minFractionDigits="0"/>
    </input> <br/>
    Range: <input jsf:id="range"  type="range" min="1" max="10"  jsf:value="#{html5Bean.range}">
        <f:convertNumber minFractionDigits="0"/>

    Date: <input jsf:id="date" type="date" jsf:value="#{}" >
        <f:convertDateTime pattern="yyyy-MM-dd"/>
    <input type="submit" jsf:id="submit" value="Save" jsf:action="#{html5Bean.submit()}">            

NOTE: In fact, this is really not a new feature. In the old facelets(before JSF 2.0), it supports a jsfcid attribute in plain HTML tags to identify a JSF component. What make me excited is it becomes standard now.

The pain of HTML 5 support in browsers

Currently only Opera supports all HTML 5 elements in this post.
The following is the result of HTML 5 required attribute validation.
the required true displayed in opera
This is the the whole form displayed in Opera.
the required true displayed in opera
In Firefox, the rangenumberdate are not rendered as expected, they are displayed as plain text input instead.
HTML 5 looks beautiful, but the browser support is a little disappointed now.
NOTE: If f:ajax is added in the *h:commandButton and the form is submit in ajax way, I found the browser native validation does not work.*

Sample codes

Check out the complete codes from my, and play it yourself.



Primefaces javascript RemoteCommand parameters


From BalusC:
Since PrimeFaces version 3.3 the syntax is as follows (copypasted from 3.3 users guide):

3.81 RemoteCommand

Passing Parameters

Remote command can send dynamic parameters in the following way;

increment([{name:'x', value:10}, {name:'y', value:20}]);

This way offers the possibility to specify multiple values on a single parameter name. Parameters with single values like above are available the same way as the old way:

private int x;
private int y;

(note: you can use Integer in Mojarra, but not in MyFaces, this is further completely unrelated to <p:remoteCommand>)

or in method of a broader scoped bean:

Map<String,String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
int x =Integer.valueOf(params.get("x"));
int y =Integer.valueOf(params.get("y"));

If you need to specify a parameter with multiple values, then you could do it as follows:

functionName([{name:'foo', value:'one'},{name:'foo', value:'two'},{name:'foo', value:'three'}]);`

with in a request scoped bean:

private String[] foos;

or in method of a broader scoped bean:

Map<String,String[]> paramValues = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterValuesMap();
String[] foos = paramValues.get("foo");


Callback Parameters

You can add as many callback parameters as you want with addCallbackParam API.

Each parameter is serialized as JSON and accessible through args parameter so pojos are also supported just like primitive values. Following example sends a pojo called User that has properties like firstname and lastname to the client in addition to isValid boolean value.
public void validate() {
//isValid = calculate isValid
RequestContext requestContext = RequestContext.getCurrentInstance();
requestContext.addCallbackParam(“isValid”, true or false);
requestContext.addCallbackParam(“user”, user);
<script type=”text/javascript”>
function handleComplete(xhr, status, args) {
var firstname = args.user.firstname;
var lastname = args.user.lastname;
By default validationFailed callback parameter is added implicitly if validation fails.


Fileuploader only uploads first file if an BlockUI component is in the same view, Primefaces

I´m using common Primefaces 3.5. with JSF 2.1 and JDK 1.7.
Application server is glassfish 3.

If i use an UIBlock component in the same view as the fileuploader, 
the fileuploader only processes the first file.
Testet with different commons-io and commons-fileuploader libs.
Testet on single view with only these two components in it.

After removing the UIBlock Element the fileuploader is working fine again.



Jul 10, 2013

#1 dpearson…

Check out the last post in this topic. 
I had a block UI file upload problem even when they weren't in the same dialog. 
It seems they are incompatible. This fixed my issue so maybe yours is related.

I overloaded the function in my own primefaces control javascript file with
Primefaces.widget.BlockUI.prototype.bindTriggers = function {
code from that post

Being able to do this is pretty handy b/c you don’t have to break open the primefaces
source and update it yourself.
I’ve had to do this for a few other issues as well that just needed some if checks.


The post:

I had the same problem. I think it is related to the fileUpload more than blockUI cause the ajaxComplete triggered has no parameter in it…Anyway i resolved this with a patch to the primefaces.js modifying the blockUI widget bindTriggers method like this:

bindTriggers:function(){var a=this,b=this.cfg.triggers.split(",");$(document).bind("ajaxSend",function(d,f,c){if(c){if($.inArray(c.source,b)!=-1){}}});$(document).bind("ajaxComplete",function(d,f,c){if(c){if($.inArray(c.source,b)!=-1){a.hide()}}})}
var a=this,b=this.cfg.triggers.split(",");




Integrate JSF 2.2, CDI with Spring Framework

Integrate JSF 2.2, CDI with Spring Framework

The integration issue between JSF and Spring

Original: by jason zhang.

JSF 2.2 comes with several cool features: html5 support, resource contracts, flow scope, etc. As a JSF enthusiast, you may want to use it in your new project or update your old project. But most likely you project already has spring MVC as it is the ‘glod’ standard.

It is always a trouble to using Spring together with JSF. JSF is a completely MVC framework while Spring WebMVC is designed for other view technology to plugin. When it comes to JSF, you will find many function duplication between MVC and JSF. This duplication will definitely cause trouble for JSF developer. For example, are you going to use Spring view mapping or JSF navigation? To handle a JSF commandButton action, are you going to use Spring WebFlow action or JSF action Listener? In a Spring WebFLow, can you still use the whole JSF process flow?

This is just the beginning of the problem. JSF 2.2 is tightly coupled with CDI for some of its new feature. For example, it uses CDI for flowScope and new ViewScope.However, Spring does not fully support CDI in JEE. I guess it will become more and more difficult in using JSF under Spring as new JSF comes out in future.

Here I did some experiment to figure out how to use JSF 2.2 besides Spring Framework. The principle is not using Spring MVC for JSF.

Using two CDI frameworks

JSF 2.2 definitely needs CDI framework if FlowScope or ViewScope is used. Please note that ViewScope has many troubles in JSF 2.1 and it is the most used scope in JSF in my opnion. So I assume that CDI is definitely needed. Spring itself is a CDI framework, but not compliant with JEE standard(JSR 330). Besides Spring, we need a JSR 330-compliant CDI libary.

Do not use Spring MVC

Do not use any Spring MVC feature for your Facelet. This means you JSF facelet page is driven by FacesServlet, not by Spring MVC DispatchServlet.

Look up Spring Bean

So how can you find Spring bean in JSF code? Here is a piece code to show this:

  ApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
  SBeanApp beanApp=ctx.getBean("sBeanApp", SBeanApp.class);
  System.out.println("found bean with desc "+beanApp.getDesc());

I post my pom.xml and web.xml to show a real project looks like:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="" xmlns:xsi="" xsi:schemaLocation="">



         <!-- Servlet Spec 3.0 -->
<!-- JSF 2.2 -->


         Enables common annotations,

             which is provided by default in an EE container, on Tomcat Begin-->      


       <!-- Spring -->

<!-- Not used for JSF, may be used for other purpose such as RESTful communication -->
      <!-- WELD -->




<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi=""

    <!-- Spring -->

    <!-- The master configuration file for this Spring web application -->


    <!-- Enforce UTF-8 Character Encoding -->


    <!-- Loads the Spring web application context -->

    <!-- JSF -->
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-name>Faces Servlet</servlet-name>

        <description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
    <!-- <context-param>
    </context-param> -->
    <!-- will be invoked automatically by Mojarra -->
    <!-- <listener>
    </listener> -->

<!-- WELD -->

        <description>Object factory for the CDI Bean Manager</description>


Problem solved. You can use your favorite JSF library and keep Spring enthusiast happy at the same time.