Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do ampersands (&) need to be encoded in JSF? Is there a way around this?

Tags:

jsf-2

I often have Javascript on my JSF XHTML pages that has && in it, which I end up having to encode as &&

For example, when I place the following in my JSF XHTML page file:

I am an & sign

I get the error:

The entity name must immediately follow the '&' in the entity reference

One wayto fix this appears to be to change the '&' to & which I find undesirable to just writing '&'.

It also appears that for cases where I use the '&' in Javascript, I can wrap the Javascript in CDATA tags; when wrapped in CDATA tags, I can then write '&' without having to escape it as &, which is a good workaround to be able to have more readable Javascript code on my page.

But what happens when I want to use the literal '&' elsewhere on the page when it is not within <script> tags and therefore cannot as easily wrap the code in CDATA tags? Must I always escape '&' as &amp; for these cases?

Note trying to use 's ability to escape values and do not seem to be able to fix the issue

like image 754
BestPractices Avatar asked Jun 18 '12 16:06

BestPractices


2 Answers

Facelets is a XML based view technology. Any characters which have special treatment by the XML parser needs to be XML-escaped when the intent is to present them literally. That covers among others < and &. The < indicates the start of a XML tag like so <foo> and the & indicates the start of a XML entity like so &#38;. The < must be escaped as &lt; and the & as &amp;.

Not escaping them in Facelets would result in the following exception for <

javax.faces.view.facelets.FaceletException: Error Parsing /test.xhtml: Error Traced[line: 42] The content of elements must consist of well-formed character data or markup.

and the following one for &

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

This is not specifically related to JavaScript, this applies to the entire view, including "plain text". Those characters just happen to be JavaScript operators as well. There's no way to go around this, that's just how XML is specified. In JavaScript, there's however one more way to avoid escaping or using CDATA blocks: just put that JS code in its own .js file which you load by <script> or <h:outputScript>.

In EL, there is also the && operator which also needs to be escaped as &amp;&amp; as well, but fortunately there's an alias for this operator, the and operator.

See also:

  • Mozilla Developer Network - Writing JavaScript for XHTML
like image 156
BalusC Avatar answered Nov 02 '22 00:11

BalusC


It's because & is special characters in XML : http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references

like image 37
La Chamelle Avatar answered Nov 01 '22 23:11

La Chamelle