JSF Tip #32 - Override a JSF Renderer

Say you have a problem with how a particular component renders and you want to do it a bit different. Well in JSF that is not a problem there is a hook-in that you can use to override how a renderer does it rendering. The sample below shows you how to do it.

You will have to do 2 things.

  1. Register your own renderer for a given renderer type
  2. Implement your own renderer

First lets make sure the JSF runtime registers your renderer.


    <?xml version='1.0' encoding='UTF-8'?>

    <faces-config version="2.1"
                  xmlns="http://java.sun.com/xml/ns/javaee"
                  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
                  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
                http://java.sun.com/xml/ns/javaee/web-facesconfig_2_1.xsd">
        <render-kit>
            <render-kit-id>HTML_BASIC</render-kit-id>
            <renderer>
                <component-family>javax.faces.Output</component-family>
                <renderer-type>javax.faces.Text</renderer-type>
                <renderer-class>org.glassfish.jsf.overrideRenderer.MyTextRenderer</renderer-class>
            </renderer>
        </render-kit>
    </faces-config>
        

Note that for your component you will have to figure out what the render-kit-id, component-family and renderer-type is. For standard components the render-kit-id will be HTML_BASIC.

And second the implementation.


    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;

    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);
        }
    }
        

Posted November 5, 2013

Up