Starting with JSF 2.0 the event system has been really improved and the declarative event handling is exposed through a tag, f:event
, and an annotation, @NamedEvent
. In this recipe, you will see how to work with these two and how to subscribe to events like preRenderComponent, PostAddToView
, and so on.
We developed this recipe with NetBeans 6.8, JSF 2.0, and GlassFish v3. The JSF 2.0 classes were obtained from the NetBeans JSF 2.0 bundled library.
Starting with the f:event
tag, we can say that this is a simple tag that should be fitted in the right place and configured with its two simple attributes. Speaking of fitting it in the right place, you should know that f:event
can be placed in any component that you want—for example we put it in an h:inputText
component:
… <h:inputText value="#{bean.number}"> <f:event type="preRenderComponent" listener="#{bean.initNumber}" /> </h:inputText> …
As you can see there are two attributes of the f:event
tag, named type
and listener
. The value of the type
attribute represents the name of the event for which to install a listener (in our example, we have used the preRenderComponent
value—with other words, before the component is rendered). In the following table are the possible values, and the corresponding event type for which the listener action is registered.
Value for |
Type of event sent to listener method |
---|---|
|
|
|
|
|
|
|
|
The listener
attribute's value represents a MethodExpression
pointing to a method that will be called when the listener's processEvent
method would have been called. In our example, that method is named initNumber
and it can be seen in the following managed bean:
package beans; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; @ManagedBean @SessionScoped public class Bean { private String number = ""; public Bean() { } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public void initNumber(){ setNumber("2010"); } }
While f:event
works only with predefined events, the @NamedEvent
provides support for exposing custom events. The application developer can make a custom event available to the page authors using the @NamedEvent
annotation. This annotation can be placed on custom events to register them with the runtime, making them available to f:event
. When the application starts, JSF scans for a set of annotations, including @NamedEvent
. If it is found on a class, the following logic is applied to get the name/names for the event: