Using Custom JSF 2.2 tags

If you are planning to use JSF 2.2 then creating custom tags is even simpler! In JSF 2.2 declaring the tag into an XML file is not required anymore an the tag declaration can be done via the component’s annotation. For this the @FacesComponent annotation introduces 3 new attributes:

  •     createTag – If set to true the component will be directly useable via a tag on a Facelet.
  •     tagName – Optional explicit name for the tag. If omitted, the class’ simple name with the first character in lowercase will be used.
  •     namespace – Optional explicit namespace for the tag. If omitted the namespace ‘http://java.sun.com/jsf/component’ will be used.

Here's your custom tag based on the JSF 2.2 implementation

package com.sample;

import java.io.IOException;
import java.util.Hashtable;

import javax.faces.component.FacesComponent;
import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;

@FacesComponent(value = "dictionary", createTag=true)
public class TranslatorComponent extends UIComponentBase {
   . . . .
}

And here's how to reference it from within your XHTML page:

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:ct="http://www.mastertheboss.com/custom-taglib">

<h:body>           
  <h:form>
         Translation: Dog is <ct:translatorComponent value="dog" />
  </h:form>
</h:body>
 
</html>

Download the code from this article.

0
0
0
s2smodern