JSF supports event handling throughout the JSF life-cycle. In this post, I use two events: postAddToView for scanning components tree and preRenderView for manipulating the meta of components before rendering to GUI.
I modified my own project from previous post for this example. This is my first further JSF trying out with the project as I said before. :)
We define the tags f:event below the form - a container component of the components which we want to work on. The valid values for the attribute type for f:event can be found from tag library document of JSF 2.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>JSF - System events Example</title>
</h:head>
<h:body>
<h:form id="helloForm">
<f:event listener="#{guiHanlder.onScanView}" type="postAddToView"/>
<f:event listener="#{guiHanlder.onManipulateView}" type="preRenderView"/>
<h:outputText value="#{helloBean.greeting}" id="greetingOutputTxt"/>
<br/>
<h:inputText value="#{helloBean.name}" id="nameInputText"/>
</h:form>
</h:body>
</html>
This is the managed bean below is just used for displaying information.
package vn.nvanhuong.jsf_myfaces;Here, I just used a method from a Java class to manipulate the components. In my future posts, I am going to try to call a Drools files instead.
import javax.faces.bean.ManagedBean;
@ManagedBean(name = "helloBean")
public class HelloManagedBean {
private String greeting;
private String name;
public String getGreeting() {
return greeting;
}
public void setGreeting(String greeting) {
this.greeting = greeting;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package vn.nvanhuong.jsf_myfaces;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlInputText;
import javax.faces.component.html.HtmlOutputText;
import javax.faces.event.PostAddToViewEvent;
import javax.faces.event.PreRenderViewEvent;
@ManagedBean(name = "guiHanlder")
public class GuiManipulatingHandler {
private ListuiComponents;
public void onScanView(PostAddToViewEvent event) {
UIComponent rootView = event.getComponent();
uiComponents = rootView.getChildren();
}
public void onManipulateView(PreRenderViewEvent event) {
for (UIComponent uiComponent : uiComponents) {
if(uiComponent instanceof HtmlOutputText){
((HtmlOutputText) uiComponent).setValue("Hello");
}
if(uiComponent instanceof HtmlInputText){
((HtmlInputText) uiComponent).setMaxlength(100);
((HtmlInputText) uiComponent).setValue("JSF system events");
}
}
}
}
I ran on Tomcat (v7) and the result looks like:
Source code: https://github.com/vnnvanhuong/jsf_myfaces/tree/jsf_system_events
Reference:
[1]. http://balusc.omnifaces.org/2006/09/debug-jsf-lifecycle.html