JSF 2.2'de olabilecek en basit bir Hello World bileşeni yapalım. Bunun için bir bileşen içine temel özellikleri sağlayan UIComponentBase sınıfını extend etmemiz gereklidir :
import java.io.IOException;
import javax.faces.component.FacesComponent;
import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
@FacesComponent(value="components.HelloWorldComponent",
createTag=true, tagName="hello", namespace="http://www.fibiler.com/jsf")
public class HelloWorldComponent extends UIComponentBase{
@Override
public String getFamily() {
return "hello.world.component";
}
@Override
public void encodeBegin(FacesContext context) throws IOException {
ResponseWriter writer = context.getResponseWriter();
writer.write("Hello World!");
}
}
Bu bileşeni artık sayfalarda kullanabiliriz. Aşağıdaki gibi kullanalım :
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:t="http://www.fibiler.com/jsf">
<t:hello/>
</html>
Sayfa çalıştırıldığında Hello World! mesajı görülecektir.
Attribute'si olan ikinci bir bileşen yapalım:
import java.io.IOException;
import javax.faces.component.FacesComponent;
import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
@FacesComponent(value="components.HelloWorldComponent2",
createTag=true, tagName="hello2", namespace="http://www.fibiler.com/jsf")
public class HelloWorldComponent2 extends UIComponentBase{
@Override
public String getFamily() {
return "hello.world.component";
}
@Override
public void encodeBegin(FacesContext context) throws IOException {
String value = (String) getAttributes().get("value");
ResponseWriter writer = context.getResponseWriter();
writer.write("Hello " + value);
}
}
Bu bileşeni de aynı sayfaya ekleyelim :
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:t="http://www.fibiler.com/jsf">
<t:hello/>
<br/>
<t:hello2 value="Fibiler"/>
</html>
Artık sayfa çalıştığında Hello World! ve Hello Fibiler yazısını görebilirsiniz.