h:outputText values with named parameters


JSF supports parameter substitution out-of-the-box, but only so far as using numbered indices, which aren’t insanely easy to read or remember. For example,

This outputs “This comes out as that.” – fine for your everyday message, but when combined with DB-driven resource bundles and dynamic parameters, this provides a world of difficulties within the opportunities provided by localisation.

With thousands of sentences containing 0’s and 1’s comes great potential for trouble. It would be preferable to refer to the parameters by name – this makes them more resilient to change,  especially in terms of changing the order of the parameters, and makes the sentences easier to read.

It turns out we can accomplish that fairly easily, by implementing a new Renderer for the outputText  tag. This renderer can actually be applied to both the outputText  / outputFormat  tags, but I’m using it on the straight outputText  for simplicity’s sake.


To register our new renderer, let’s call it  za.co.knowles.renderer.CustomOutputTextRenderer , all we have to do is add a section to the faces-config.xml .

This automatically becomes the renderer for all outputText  tags.

Our renderer extends the supplied Renderer class, and all we need to override is the getEndTextToRender  method. This method is called just before the text is rendered to the screen, so if we modify the text with our substitution and call the super-class method then our ends are met with minimal fuss.

We extract the parameters from the original UIComponent , then pass them on to our substitution code. To extract the parameters, we iterate through the children and extract their names and values, then put them in a POJO we’ve created called Parameter  that stores names and values.

At this point we have the original text (potentially with {‘s and }’s indicating substitution) and we have a range of (or no) parameters. This is now straight String manipulation, decoupled from anything JSF specific – we extract the parameters with a RegEx, then replace them with the parameter values we pass in.


Tagged with: , , ,
Posted in Java

Leave a Reply