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

后端 未结 4 1674
耶瑟儿~
耶瑟儿~ 2020-12-01 23:34

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

相关标签:
4条回答
  • 2020-12-02 00:14

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

    0 讨论(0)
  • 2020-12-02 00:21

    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
    0 讨论(0)
  • 2020-12-02 00:29

    This code worked for me :

    <h:outputText value="&amp;copy;" escape="false" />
    
    0 讨论(0)
  • 2020-12-02 00:35

    FYI, I tried to write the (c) character in my JSF page. An error was raised when I wrote &copy : "copy is referenced but not declared" When I wrote &copy; I got the raw string back.

    I could display the special character using the unicode notation : ©

    0 讨论(0)
提交回复
热议问题