Sunday, 10 November 2013

GenericMessage for DeltaSpike supporting JSF and REST


In the post of January 2013, I described the feature of DeltaSpike to have type safe messages from within a CDI bean which are displayed within the <h:messages> tag of JSF.
It is a great feature which has a minor drawback, especially in the perspective of Java EE as a universal backend system. (see this post for the idea behind this)
In the case a CDI bean, like a service type of bean, is used in the context of JSF and REST contexts, because you have multiple types of clients, there is an issue with JsfMessage of DeltaSpike.

Custom version

Since DeltaSpike is an open source project, you can easily find out how the feature is coded. And you can create something similar which isn’t tied to JSF quit easy as you can see in this post.
First we need to define the alternative for the JsfMessage interface, lets call it BusinessMessage.
public interface BusinessMessage<T> {

    T failing();

    T warning();

    T information();

We have 3 methods, so that we can define an error, warning and information message. 

The usage of this interface will be identical to the JsfMessage one of DeltaSpike.  Se we need to define an interface which will be annotated as MessageBundle and we are ready to use it.
public interface ApplicationMessages {

    @MessageTemplate(value = "Person already registered")
    String personAlreadyRegistered();

public class AttendeeService {

    private BusinessMessage<ApplicationMessages> message;

    public void addPerson(Person person) {

Within the implementation of the BusinessMessage interface we will make, we can now make sure it will work within a JSF and REST context.

BusinessMessage implementation details

I’m not going to describe all the implementation details in this post.  In a few weeks, the code of a demo application will be made available that highlights almost all of the things that kept me busy the last year. And it is using the BusinessMessage described here.

The code is using the org.apache.deltaspike.core.impl.message.MessageBundleInvocationHandler class of DeltaSpike to have a dynamic implementation of the @MessageBundle annotated interfaces like ApplicationMessages we have in the above example block.

Once we have the message text the user wants, we will store it in a Thread local variable, maintained by a new class BusinessMessageContext.  This class makes it possible to keep some messages independent of the view technology used. So it is supporting JSF and REST style of working.

Show the messages

The last step to solve our issue is that we need use the messages stored in the BusinessMessageContext and send it to the correct view.

For JSF we can create a PhaseListener implementation which is triggered before each Render Response phase.  It can add the messages to the JSF system using the facesContext.addMessage method.

For REST, we can use a concept explained in this post, to send the messages to the client as a JSON response. Some of the aspects will be described in more detail in a future post on that blog.

In both cases, we need to do the clean up of the Thread local variable we have used to store the messages to reclaim the memory.  Therefor the class BusinessMessageContext has a method release() to perform this clean up.


JsfMessage of DeltaSpike is a great feature to have type safe messages. But in some cases your CDI bean will be used in multiple ‘environments’, JSF and REST for example. In that case, we need an alternative which works almost the same but stores the messages, at least initially, in a view neutral way.

Code will be available as part of the demo which will be released in a few weeks.

Tuesday, 8 October 2013

How to debug javascript in PrimeFaces 4.0


With each new release of PrimeFaces, the JavaScript becomes more and more important in the framework.
This is no surprise as JavaScript is needed to give the end user a rich user interface. And in the latest release there is quit a lot of new JavaScript code added for the client Side validation framework.
But if you want to debug it in the browser, you see that the code is minified. And thus stepping through it line by line is not possible.
This post describes how you can do it.

Build custom version

The source code of PrimeFaces contains the human readable code and the idea is that we build a custom jar file which contains that readable version of the JavaScript.
As the code is open source, it is available on Google code. We can do a checkout with following command.
svn checkout

Now we go to the pom.xml file and make some small changes.
The most important one is the change of the version tag.  I have changed it to 4.0-DEBUG (you can find it at the top of the pom.xml file)
PrimeFaces uses a maven plugin to generate the JSF components and configuration files. 
This plugin is located in the PrimeFaces maven repository which you must include into the pom file. Otherwise the build will fail.
When you now execute the mvn install command, you will have a customized version of PrimeFaces in your local Maven repository which contains the non minified version of JavaScript.

Using this version in your project, by specifying it in a profile so that it doesn’t go into production, you can do debugging in your favourite browser.


We following the above steps, you have a custom version of PrimeFaces where the JavaScript is not minified and thus can be debugged in the browser. Of course it is not suited to go to production with this version.

Wednesday, 25 September 2013

Generic JPA 2.1 converter for enum


Until now, an enum value could be stored in the database by its ordinal number or his name in JPA. When you have a ‘legacy’ database or when you are doing refactorings you could be in trouble.  The only option then was to rely on the implementation to allow a custom value as the representation of the numeration in the database.
In the latest release of JPA, 2.1, there is support for custom converters so you can solve these kind of issues.

JPA 2 Converter

What do you need to do to have a custom converter? The enumeration class doesn’t need any change. In the entity were you use the enum, you need to specify the converter you like to use, like this:
public class Person {

  @Convert(converter = GenderEnumConverter.class)
  private Gender gender;

The converter class can look as this
public class GenderEnumConverter implements AttributeConverter< Gender, String> {

  public String convertToDatabaseColumn(Gender attribute) {
    String result = "";
    switch (attribute) {

      case MALE:
        result = "M";
      case FEMALE:
        result = "F";
    return result;

  public Gender convertToEntityAttribute(String dbData) {
    Gender result = null;
    switch (dbData) {
      case "M":
        result = Gender.MALE;
      case "F":
        result = Gender.FEMALE;
    return result;

And the last thing you need to do is to ‘register’ the converter with JPA as no scanning is performed of the available classes.  You can specify the class name, just as you specify the entity classes in the persistence.xml file.
<persistence-unit name="converter-unit" >
  <description>Forge Persistence Unit</description>


Not OO

The above code is not ideal in several ways. If you have an enum class with a lot of values, you have to write a large if-then-else structure which is not very OO like. And you also need to write a lot of similar code which wants me to search for a more generic solution.

If we could define the database value together with the enum value, it would be a great improvement. It makes the code also much more logic as you can define the database value together with the enum value.

Since we need such functionality for each numeration that we use in the persistent objects, we can create an interface like DatabaseEnum.
public interface DatabaseEnum {

  Serializable getDatabaseValue();


And change the enum to implement this interface.
public enum Gender implements DatabaseEnum  {
  MALE("M"), FEMALE("F");

  private Serializable databaseValue;

  Gender(Serializable databaseValue) {
    this.databaseValue = databaseValue;

  public Serializable getDatabaseValue() {
    return databaseValue;


This should allow us to create a generic converter for the enums, except that the Java compiler removes the information regarding the generic types, know as type erasure. Otherwise a converter like this could be possible.
public class EnumConverter<T extends DatabaseEnum> implements AttributeConverter< T, Serializable> {

  public Serializable convertToDatabaseColumn(T attribute) {
    return attribute.getDatabaseValue();

  public T convertToEntityAttribute(Serializable dbData) {
    // There is no way we can create such a method
    return determineEnum(T, dbData);


If we would be able to define that a custom constructor needs to be called, where we supply as parameter the class T, we would get away with it.  But this is not the case.
public EnumConverter(Class<T> enumType) {..}

Almost generic converter

Based on the optimal code above, we are able to create a converter that uses a generic utility method.  It means that we still need to create a converter for each enum class we like to use, but the code is much cleaner then the first example we show in the text.
public class GenderEnumConverter implements AttributeConverter<DatabaseEnum, Serializable> {

  public Serializable convertToDatabaseColumn(DatabaseEnum attribute) {
    return attribute.getDatabaseValue();

  public Gender convertToEntityAttribute(Serializable dbData) {
    return DatabaseEnumUtil.getEnumValue(Gender.class, dbData);

And the utility method can be small and generic thanks to the not very known method getEnumConstants() of the JVM core classes.
  public static <T extends DatabaseEnum> T getEnumValue(Class<T> enumClass, Serializable dbValue) {
    T result = null;
    if (dbValue != null) {

      for (DatabaseEnum enumInstance : enumClass.getEnumConstants()) {
        if (dbValue.equals(enumInstance.getDatabaseValue())) {
          result = (T) enumInstance;
    return result;


In the latest version of JPA, a custom converter can be defined which can be very handy in a lot of situations.  You can use it to create a converter for Joda-time classes or for specifying the database value of an enum value.

The only thing that keeps us from creating a generic converter for enums is the type erasure thing of Java. Otherwise we could create a beautiful converter for all our enums.

Monday, 5 August 2013

From CODI to DeltaSpike


CODI is my favourite CDI extension framework where you can find all kind of goodies when you are working in a CDI environment.
Some time ago, there was a decision to create a new CDI extension framework which brings together all the good features of CODI and Seam 3 and other features from other CDI extension libraries.

They have gone through the incubation process at Apache and moving along steadily. The question is, can you already switch from CODI to DeltaSpike for an application?

Not all features of CODI are implemented but my 2 favourites ones are
- The additional scopes like ViewAccessScope
- The fluent API for adding FacesMessages.
So can we create a DeltaSpike application with these 2 features.


In the current version of the DeltaSpike framework, version 0.4, there is no support for something like the CODI's ViewAccessScope .
Therefor, Gerhard Petracek created an extension for DeltaSpike to have the missing scopes from CODI version 1.0.5 into DeltaSpike. See here.
So adding the required dependency to the POM

  <name>Gerhard personal repository</name>


The version of the extension is a concatenation of the 2 libraries it will bridge. So we have the structure  &CODI version&_&DS version&_&extension version&.

You only have to use the new package name to have the additional CODI scopes.  The API is identical so that existing code which works for CODI, will also work with DeltaSpike.

So for example for ViewAccessScope,

import org.apache.myfaces.extensions.cdi.core.api.scope.conversation.ViewAccessScoped;

import org.os890.cdi.ext.scope.api.scope.conversation.ViewAccessScoped;
So for any of the scope packages, you have to replace org.apache.myfaces.extensions.cdi.core with org.os890.cdi.ext.scope.


The support for a fluent messaging API is already present in DeltaSpike. So to have this kind of functionality, we don't need to use an extension as we did for having the scopes.

But here we have the issue that the API is changed and thus we need to adapt existing code.

CODI version


DeltaSpike version

Message defitions.
public interface AppMessages {
    String buttonClicked();

Within CDI bean
    private JsfMessage jsfMessage;

    public void addTestMsg(ActionEvent actionEvent) {


 The DeltaSpike application was tested successful on Glassfish and JBoss as 7.1.1.Final.

Also the original CODI version was running without a problem on the new Glassfish 4 version.

On this server, the DeltaSpike version had a problem.  There was an exception thrown in the extension as there is no problem with the DeltaSpike code itself. All the integrations tests of DeltaSpike are running also on a Weld 2 version (used in the Glassfish 4) so you can expect that it is working on it without any problem.

With the new WLS 12C server, version 12.1.2, there is also an issue running the DeltaSpike application.   The application deployment fails during validation where it can't inject an Extension class into another bean.


With the help of the DeltaSpike extension, you can create already applications that uses a lot of the features of the CODI framework.
So check what features you need and maybe you can already create your application with the DeltaSpike framework.

Friday, 7 June 2013

JSF 2.2 Pass-through attributes


Until now, you could only use attributes on the JSF tags which where recognized by the component library.
Until recently, this made sense.  Those attributes are used to ‘configure’ the JSF tag and thus other attributes have no meaning for the component and thus not needed.
But that changed with the HTML 5 specification. One of the additions is that you can define and use your own attributes which can be used by for instance by your javascript code.
Now you no longer need to use class names to store metadata and thus your html code becomes cleaner.

JSF support

But this nice feature of HTML5 is a problem for the JSF framework. Since we have no way of specifying that additional parameters needs to be passed to the generated markup, there was no easy way of supporting them.
Of course you could define them with the <f:attribute> tag and write extensions for the renderers, but native support is of course needed.
And with the new JSF 2.2 specification, there is the possibility to support them.  The feature is called pass-through attributes. And technically that is also what is happening.  Those attributes are just passed to the generated markup.

Example, input placeholder

Now we can specify the hint for an input with the placeholder attribute without the need of the component library to support it (of course, our browser need to support the HTML 5 attribute)
<html xmlns=""
        <h:inputText id="basic" value="#{bean.value}" p:placeholder="Enter text"/>

By marking attributes as belonging to the newly introduced namespace, we tell the renderers that they need to copy it to the markup.  Besides the support for literal values (like in the example above) EL expression are also allowed.

As you can see, they have also changed the namespace to instead of to emphasis that the specs are a community process and not originating from a single company (or was it just to remove the name sun?).

Multiple attributes

If you have several pass-though attributes that you need to specify, there is another way of specifying them.

The core namespace (xmlns:f="") has an additional tag now, called passThroughAttributes. It has a reference to a Map that contains all the attributes that needs to be added. The key of the map must be of String type, the value is an object or EL expression.
<f:passThroughAttributes value=”#{service.nameValuePairs}” />

You no longer need to specify them one by one, but the drawback of it, if you ask me, is that those view related metadata is specified in Java code and not in the JSF view.

Support in component libraries

For those that are writing component libraries them self (or a few components), it is easy to support those pass-through attributes on your component as well.

On the UIComponent class, they have introduced a new method getPassThroughAttributes(boolean) that you can use to retrieve the discovered attributes.

It returns the info as a Map and you can iterate over this collection and write the information on the response stream.

As this approach is generic, you can put the code in a utility class/method and call it for every component you like to have support for the pass-through components.


With the new pass-through feature of the JSF 2.2 spec, it becomes easy to support the HTML5 data attributes.  It is as simple as specifying the attributes on the JSF tag prefixed with an alias for a specific namespace to identify them as pass-through.

Also the code to support the in your custom widgets is less then 10 lines long.

The only issue you could have is that for some JSF components, it is not always immediately clear where the pass-through attributes are placed in the HTML markup when the tag generates multiple JSF elements.

Monday, 13 May 2013

JSF 2.2 Stateless views explained


The JSF 2.2 specification (JSR-344) is recently approved. There are a few examples available but there seems no detailed explanation yet of the new features.
Although the development is still in progress, I like to start today already with the stateless view features which was fairly late added to the list of JSF 2.2 features.
The ticket had many votes and stateless is hot, so for many people this is a very wanted feature which is added.
But be aware of the implementation details and some other facts that are very good explained in this section of the excellent overview of Arjan Tijms on JSF 2.2 features.


The explanation of the feature is fairly simply. By specifying the attribute transient on the f:view tag, we are able to run that page in a stateless mode. Stateless here means that the JSF StateManager isn’t storing any data into the memory related to this view.
During restore view phase, the view is created, as always, but now there isn’t any state applied to it.
It is a fairly simple change but has a lot of consequences.

viewScoped beans

The most important effect of the stateless operation mode is that all viewScoped beans are lost. Those kind of beans, tied to a certain view, aren’t stored anymore and thus, when the same page is rendered again, a new version of the bean needs to be instantiated again.
It can easily demonstrated by a ‘classic’ scope testing application, for example the one I used here to test CODI on WLS 12c server. You create beans with a different scope, like requestScope, viewScope, sessionScope and applicationScope and initialize a timestamp in the constructor.  The value of this property is then shown on screen where you can do a post to stay on the same page or go to another page which has the same beans on it.
In the case of the transient view, even if you stay on the same page, a new instance of the viewScoped bean is created. The other scopes aren’t affected.
I tried this with the Glassfish 4 promoted build 87 and a Tomcat 7 instance where I used the latest available Mojarra 2.2 snapshot.

viewScope != viewScope

Although not immediately linked to the stateless view features, there are now 2 ViewScoped annotation classes. We had already the RequestScoped, SessionScoped and ApplicationScoped from JSF (package javax.faces.bean) and the CDI version (in package javax.enterprise.context).
As requested by many developers, there is now also a CDI version of the ViewScoped (from package javax.faces.bean) but defined in JSF (and not CDI). The new class is defined in javax.faces.view. Look careful to import the correct class in relation to the @ManagedBean or @Named annotation because mixing them will lead to unexpected behaviour.

When to use

What are the use cases for the stateless view operation mode. As already mentioned in the feature description by Arjan Tijms, performance and memory gain is minimal, except when you are working with very large pages that contains thousands of components.
Besides the fact that ViewScoped beans behave differently, a lot of components are relying on the fact that they can save and restore their state within the view. So many components, standard ones but also from component libraries like PrimeFaces will not function properly anymore on stateless views.
On the other side, views are stateless and this means you can even post your data back to the server, after your session has expired or even after a server reboot.


Since there is a large impact on AJAX behaviour, commonly used with ViewScoped beans, and the proper functioning of components, considering stateless views must be evaluated thoroughly and tested very profound.
And initiatives like the one from Industrie IT should also be considered when you are interested in those kind of setups.

Thursday, 14 February 2013

Client Behavior functionality with JSF 2.x (part 2)


In the previous text, I described how you can create a button that ask for a confirmation.  It showed the basic functionality of creating reusable client side functionality.
The example was very simple, just requiring one javaScript command.
In this text, I'll show some more advanced usages where you need to include an external resource and have to respond on multiple events.
The example shows how you can create the hover functionality for an input field. And of course with most browsers you can specify it as a css selector
    .myHover:hover {
        background-color: red;
Unfortunately, not all browsers supports this and it is a pity that IE9 fails to understand it. So lets write an universal hover functionality.

Specify the event

For the change of color when the mouse is over a field, we need to respond to 2 events.  The mouse that enters the field, mouseover event, to adjust the color and when the mouse leaves the field, mouseout event, to revert the color to his original one.
So we need a client behaviour tag, just like the confirmation tag we have created the last time, lets call it hover so that we can attach the functionality to a field.  We have 2 events but we don't need to create 2 different tags. We are able to retrieve the intended event in the getScript method.
So let start with the definition of the tag in the facelet tag library
This is identical to the confirmation functionality.  And we can use it in the following way
        <h:inputText value="#{bean.prop}" >
            <custom:hover event="mouseover"/>
            <custom:hover event="mouseout"/>
We now specify the events we like to intercept and based on the event name, we can code the required javaScript        
    public String getScript(ClientBehaviorContext behaviorContext) {
        if (MOUSEOVER_EVENT.equals(behaviorContext.getEventName())) {
            return "this.className += ' hoverClass '";
        if (MOUSEOUT_EVENT.equals(behaviorContext.getEventName())) {
            return "this.className = this.className.replace( /(?:^|\\s)hoverClass(?!\\S)/g , '' )";
        return null;
The event name is passed to the getScript method in the behaviorContext parameter. The code adds or removes a CSS class to the HTML element. So when the hoverclass is defined as a red background, the input text element becomes red when the mouse is over the field and returns to his 'normal' color when we move out of it.

A single tag

The above solution is from a developers perspective not an ideal situation. The first improvement we will make is that you only need to specify 1 tag, and not 2.
The hover tag we created earlier was explicitly linked to the client behaviour functionality.  You can also create a tag for other purposes like a converter or your new component.  But there is also the possibility to create a tag for which you must implement the functionality, like this

Within the HoverHandler, you must program the behaviour that you want. Before you can start with it, you must know what the function of a handler class is.

This class will be used by the JSF system to convert the xhtml page to the component tree. Afterwards this component tree will be converted to the HTML which is sent to the browser in the Render Response phase of the JSF lifecycle.
With a handler class you can change the created component tree. You can manipulate the 'DOM tree' (or what will become the DOM tree) by adding, removing and rearranging nodes but also change the properties of the nodes in the component tree.
The HoverHandler looks like this
public class HoverHandler extends TagHandler {
    private HoverBehavior mouseOver = new HoverBehavior();
    private HoverBehavior mouseOut = new HoverBehavior();
    public HoverHandler(TagConfig config) {
    public void apply(FaceletContext ctx, UIComponent parent) throws IOException {
        if (parent instanceof ClientBehaviorHolder) {
            ClientBehaviorHolder comp = (ClientBehaviorHolder) parent;
            comp.addClientBehavior("mouseover", mouseOver);
            comp.addClientBehavior("mouseout", mouseOut);
If you want to create a tag handler class of your own, you should extend it from javax.faces.view.facelets.TagHandler and do your work in the apply method. The method has a parameter parent and it is the immediate parent of the tag. In our case, the inputText.
Since we now have a reference to the component we like to modify, we can call the addClientBehavior method twice, once for the mouseover event and once for the mouseout event.
The HoverBehaviour class we pass along with the event names, is the same class as we used in the previous section.  So it will generate the correct javaScript code for each event.
So now we have improved our hover functionality greatly from a developers standpoint.  He doesn't have to type the event names (strings where he can make mistakes) and has to type a lot less characters.

Resource dependency

The only thing that can go wrong now, is the definition of the CSS class.  If we define it in the CSS file of the application, we have it available on every page.

But what if we decide to create some kind of reusable library so that we can use it for all the applications of the company. Or what if the javaScript code is large and we have placed it in an external file?
Maybe you know already that with a JSF renderer, you can specify the external resources the renderer depends on. Resources like javascript files and CSS files, just as we also need for the client behaviour functionality.
The good news is that there exists a special renderer for client behaviour, called ClientBehaviorRenderer.  It has also a getScript method that we need to implement and we can specify the resources we need with the ResourceDependency annotation.  This is the renderer version of the hover functionality
@ResourceDependency(name = "hover.css")
public class HoverBehaviorRenderer extends ClientBehaviorRenderer {
    private static final String MOUSEOVER_EVENT = "mouseover";
    private static final String MOUSEOUT_EVENT = "mouseout";
    public String getScript(ClientBehaviorContext behaviorContext, ClientBehavior behavior) {
        if (MOUSEOVER_EVENT.equals(behaviorContext.getEventName())) {
            return "this.className += ' hoverCls '";
        if (MOUSEOUT_EVENT.equals(behaviorContext.getEventName())) {
            return "this.className = this.className.replace( /(?:^|\\s)hoverCls(?!\\S)/g , '' )";
        return null;
It is a straight copy, only the base class is different and has other annotations.
The client behavior itself becomes now empty, except for the definition of the renderer that must be used.
@FacesBehavior(value = "hover")
public class HoverBehavior extends ClientBehaviorBase {
    public String getRendererType() {
        return "hover";

Wrap up

We now have created a custom tag which allows us to have the 'hover' functionality using javascript functionalities. We only need a single tag and due to the renderer approach, we can package it in a jar file. When the file is in the classpath and we use the template, the correct coloring is applied to the 'hovered' field.


With the client side behavior of JSF 2, you have the possibilities to further enhance the components in a component library with some client side features in a reusable way. JSF remains mainly a server side framework but the client side representation can now greatly enhanced by the developer.
With these possibilities available, JSF can go along with the recent HTML5 and JavaScript frameworks raise in interest in the application development business.

You can find the code for this tutorial here.

Sunday, 3 February 2013

Client Behavior functionality with JSF 2.x (part 1)


One of the lesser know new features of JSF 2, is the ability to define some client behavior for a component in a reusable way. We all know the possibility to enhance a component with ajax, using the tag.  It is also based on the Client Behavior functionality but we can define our custom functionality.

Just as you can define a validator for an input field, you can define a behavior which results in some JavaScript code which can be executed in the browser.

These features shows that, although JSF is still mainly a server side framework, the importance and the popularity of the client side is acknowledged.

Confirm button

We start with a simple example where we like to make a button that first asks for a confirmation before it performs its action.  A classic example is the button that deletes some information but first we ask the user for a confirmation if he is sure to execute this irreversible action.

The key Java class for the Client Behavior is ClientBehaviorBase. It implements the ClientBehavior interface, common to all functionality related to client side behavior, and by implementing the getScript method, half of the work is already done.
For our confirm functionality, we have a method like this

    public String getScript(ClientBehaviorContext behaviorContext) {
        return "return confirm('Are you sure ?');";

The return string is the JavaScript we like to execute in the browser, here it is the confirm method which pops-up a javascript ‘window’ with an OK and Cancel button.

When the class is annotated with @FacesBehavior, The JSF system add our class to the list of implemented client behaviors.

@FacesBehavior(value = "confirmation")
public class ConfirmBehavior extends ClientBehaviorBase {

The content of the value member is the, unique, name we can use to refer to our custom client behavior.  This is needed when we define a tag for the behavior.

A tag is needed so that we can specify in the xhtml files which components receive our javascript. In the facelet tag library we can define it as follows.



The behavior-id must match the value member of the FacesBehaviour annotation.  The tag name can be freely chosen but here it happens to be the same as the behavior id.

Assigning to a commandButton is not different than using any other custom tag that you have defined in a facelet tag library.

<html xmlns=""
        <h:commandButton value="with confirmation" actionListener="#{bean.performAction}">

When the user clicks now on the button, a confirmation is asked with the text ‘Are you sure?’. And when he clicks on the cancel button, the action listener method isn’t performed. In the case he has pressed on the OK button, the post to the server is executed as usual.

Which components

To what components can we attach a custom client behaviour? This is determined by the ClientBehaviourHolder interface.  It has a few methods to handle the addition and retrieval of registered client behaviors and event names. More on event names in the next section.

Well almost all components implement that interface.  The most useful ones are of course all the input fields and the buttons. But also on the html body component we can attach a behaviour. More specifically, the load event can be used to attach some additional code to the page when rendered in the browser.

How to specify the event?

In our example with the confirmation question, the javascript method is attached to the onClick method of the button.  This is because the click event is the default event for the commandButton component. If we like to attach the code to some other event, then we have to specify the event name with the event attribute of the tag. We will see an example of it in the second part of this blog.

What are all the events which are supported? This differs from component to component. But the rule is that when you have the onXXX attribute on a component to attach some behaviour, the event XXX is available for creating a reusable client behaviour with the technique explained above.


It is very easy to specify some client behavior in a repeatable manner with JSF 2. And in the second part of this text I’ll explain some more advanced topics of the client behavior functionality.