【问题标题】:Thymeleaf rendering error when using ampersand in script tag在脚本标签中使用 & 符号时 Thymeleaf 渲染错误
【发布时间】:2016-05-30 01:47:53
【问题描述】:

我想将 google map javascript 添加到 Thymeleaf 模板,如下所示:

https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places

抛出异常:

org.xml.sax.SAXParseException; lineNumber: 209; columnNumber: 93; The reference to entity "key" must end with the ';' delimiter

我尝试将& 更改为&,但没有任何改变。

您的帮助将不胜感激。谢谢!

【问题讨论】:

  • 因为 Thymeleaf 模板是 XML,你应该在属性值中使用 & 而不是 &
  • 您必须将 & 编码为 &。因为 &是 & 的转义序列,XML 会发现它是文字。

标签: java spring-mvc web thymeleaf


【解决方案1】:

你有一些选择:

1) 根本不要使用th:src

2) 由于 URL 是绝对的,因此您可以使用静态方法将其添加到服务器端:

<script th:src="${@urlService.getMapsUrl()}">...</script> 

3) 使用rewrite filter

不确定问题是否在 Thymeleaf 3 中得到纠正,但值得快速升级并查看一下。

【讨论】:

    【解决方案2】:

    Thymeleaf 使用 XML 解析器,字符 &amp;amp; 被认为是 XML 中的特殊字符。您必须将 &amp;amp; 替换为其 XML 等效的 &amp;amp;。您的 URL 将是:

    https://maps.googleapis.com/maps/api/js?v=3.exp&amp;libraries=places
    

    在 thymeleaf 3 中,这不是问题,因为他们为 thymeleaf 编写了一个新的解析器。

    【讨论】:

    • 嗨@Aboodz,我试过了,但它对我不起作用......谢谢你的回答
    • @Aboodz ,在这种情况下 Spring 返回 400。必需的参数 'someParam' 不存在。
    【解决方案3】:

    这是 Thymeleaf 中的一个错误,但自 2.1.4 以来已修复。

    看看这个issue。 (this question中描述的问题)。

    【讨论】:

    • 感谢您的回答,@sanluck !实际上我使用的是 2.1.4 版本,但问题仍然存在..
    • 像这样:
    • 我觉得应该是这样的:&lt;script type="text\javascript" th:src="https://maps.googleapis.com/maps/api/js(v=3.exp,key=xxx,libraries=places)"&gt;
    • see this file我发布的网址不正确,应该是&lt;script type="text\javascript" th:src="@{https://maps.googleapis.com/maps/api/js(v=3.exp,key=xxx,libraries=places‌​)}"&gt;
    • 它会抛出这样的异常org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as expression: "@{https://maps.googleapis.com/maps/api/js(v=3.exp,key=xxx,libraries=plac‌​es‌​)}"
    猜你喜欢
    • 2015-08-11
    • 2019-05-17
    • 2015-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-18
    • 2016-12-13
    • 1970-01-01
    相关资源
    最近更新 更多