Why do ampersands (&) need to be encoded in JSF? Is there a way around this?
It's because & is special characters in XML : http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
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 &
. The <
must be escaped as <
and the &
as &
.
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 &&
as well, but fortunately there's an alias for this operator, the and
operator.
See also:
- Mozilla Developer Network - Writing JavaScript for XHTML
FYI, I tried to write the (c) character in my JSF page. An error was raised when I wrote © : "copy is referenced but not declared" When I wrote © I got the raw string back.
I could display the special character using the unicode notation : ©