26

How to insert special characters like & and < into JSF components value attribute ?

For example: I want something like this:

<h:outputText value="Tom & Jerry Show" />

When I try this, I get the following exception:

javax.faces.view.facelets.FaceletException: Error Parsing /foo.xhtml: Error Traced[line: 15] The entity name must immediately follow the '&' in the entity reference.

And in case of <, I get the following exception:

javax.faces.view.facelets.FaceletException: Error Parsing /foo.xhtml: Error Traced[line: 15] The value of attribute "value" associated with an element type "h:outputText" must not contain the '<' character.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Rajat Gupta
  • 25,853
  • 63
  • 179
  • 294

1 Answers1

64

You need to escape them to XML entities.

<h:outputText value="Tom &amp; Jerry Show" />

This problem is not related to JSF per se, but to the view technology. You're apparently using Facelets (which is perfectly fine!). Facelets is however a XML based view technology, so you would need to ensure that the template is well formed XML and that all special characters which are to be represented as-is, are been escaped like above.

In the wikipedia you can find a list of predefinied character entities which needs to be escaped in the XML whenever you'd like to display them as-is. It are the following character entities:

"     &quot;
&     &amp;
'     &apos;
<     &lt;
>     &gt;

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • thanks!!! i'm switching between rails and legacy jsf/j2ee development and this completely slipped my mind. thanks for the reminder! – techbrownbags Jan 22 '16 at 21:26
  • great answer, as usual, but what about if I need to render a special character like a vowel with an accent mark? (so common in my language!!). Usually I'd do: `á` which renders `á`. Please how can I achieve this in JSF, in both: plain text scenarios and, for example, an `h:link`'s `value` attribute?. Thanx – Scaramouche Apr 22 '19 at 00:14
  • 1
    @Scaramouche: Just type the `á` right away in the file and save it. We're not in 1990 anymore. You can safely save files as UTF-8 (as long as your editor is correctly configured to do so). XML uses already by default UTF-8. XML entities are only needed for XML-special characters such as the five listed in the answer, not for others. – BalusC Apr 22 '19 at 11:28