为什么与号 (&) 需要在 JSF 中编码?有没有解决的办法? [英] Why do ampersands (&) need to be encoded in JSF? Is there a way around this?

查看:15
本文介绍了为什么与号 (&) 需要在 JSF 中编码?有没有解决的办法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 JSF XHTML 页面上经常有 Javascript 和 &&在其中,我最终不得不将其编码为 &&

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

例如,当我将以下内容放入我的 JSF XHTML 页面文件时:

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

I am an & sign

我收到错误:

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 '&'.

似乎对于我使用&"的情况在 Javascript 中,我可以将 Javascript 包装在 CDATA 标签中;当包裹在 CDATA 标签中时,我可以写&"无需将其转义为 &,这是一个很好的解决方法,可以在我的页面上拥有更易读的 Javascript 代码.

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.

但是当我想使用文字 '&' 时会发生什么如果它不在 <script> 标签内,因此不能轻松地将代码包装在 CDATA 标签中?我必须总是转义&"作为这些情况的 &amp; ?

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

推荐答案

Facelets 是一种基于 XML 的视图技术.任何由 XML 解析器进行特殊处理的字符都需要进行 XML 转义,以便按字面意思呈现它们.其中包括 <&.< 表示像这样的 XML 标记的开始 & 表示像这样的 XML 实体的开始&#38;.< 必须转义为 &lt;& 必须转义为 &amp;.

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;.

在 Facelets 中不转义它们会导致 <

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] 元素的内容必须由格式正确的字符数据或标记组成.

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.

以及以下用于 &

javax.faces.view.facelets.FaceletException: Error Parsing/test.xhtml: Error Traced[line: 42] 实体名称必须紧跟在&"之后在实体引用中.

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

这与 JavaScript 没有特别的关系,这适用于整个视图,包括纯文本".这些字符恰好也是 JavaScript 运算符.没有办法解决这个问题,这就是 XML 的指定方式.然而,在 JavaScript 中,还有另一种方法可以避免转义或使用 CDATA 块:只需将该 JS 代码放在它自己的 .js 文件中,您可以通过

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆