Skip to main content

JSF Tip #34 - Override JSF renderer and create a new tag for it

Posted by mriem on November 7, 2013 at 7:39 AM PST

When I posted JSF Tip #32 - Override a JSF renderer Twitter user @john_waterwood asked me how you would define a new tag for an existing component and the overridden renderer. Well it is fairly easy, see the 2 steps below!

1. Create your renderer
2. Register it

Creating your renderer

package org.glassfish.jsf.overrideRenderer;

import java.io.IOException;
import javax.faces.component.UIComponent;
import javax.faces.component.UIOutput;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.render.Renderer;

@FacesRenderer(rendererType="myText")
public class MyTextRenderer extends Renderer {

    @Override
    public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
    }

    @Override
    public void encodeChildren(FacesContext context, UIComponent component) throws IOException {
    }

    @Override
    public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
        ResponseWriter responseWriter = context.getResponseWriter();
        UIOutput output = (UIOutput) component;
        String value = "Let's be funny: " + output.getValue().toString();
        responseWriter.writeText(value, null);
    }
}

Register it

<?xml version="1.0" encoding="UTF-8"?>
<facelet-taglib xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:xi="http://www.w3.org/2001/XInclude"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facelettaglibrary_2_0.xsd"
   version="2.0">
    <namespace>mynamespace</namespace>
    <composite-library-name>m</composite-library-name>
    <tag>
        <tag-name>myOutputText</tag-name>
        <component>
            <component-type>javax.faces.HtmlOutputText</component-type>
            <renderer-type>myText</renderer-type>
        </component>
     </tag>
</facelet-taglib>

And that is it.

Enjoy!

Related Topics >>