首页 > 解决方案 > 使用 Spring 转义 HTML 中的撇号

问题描述

我在一些遗留代码中有错误,在尝试修复它时,我发现了我不理解的行为。该应用程序是一个使用 JSP 和 JSTL 的 Spring MVC 应用程序。以下是一个简化的示例,它重现了我正在谈论的行为。我的控制器的代码是:

@GetMapping("/users/thing")
public ModelAndView thing() {

    ModelAndView model = new ModelAndView("users/thing");
    String stringWithApostrophe = "Any'String";
    String escapedWithHtmlUtils = HtmlUtils.htmlEscape(stringWithApostrophe);

    model.addObject("stringWithApostrophe", stringWithApostrophe);
    model.addObject("escapedWithHtmlUtils", escapedWithHtmlUtils);
    return model;
}

该变量stringWithApostrophe中有一个撇号字符,然后我将其转义并将转义值存储在其他变量中。之后,我将它们都添加到模型中。

我的看法是这样的:

<p><a onClick="clicked('${stringWithApostrophe}');" href="#">stringWithApostrophe: ${stringWithApostrophe}</a></p>
<p><a onClick="clicked('${escapedWithHtmlUtils}');" href="#">escapedWithHtmlUtils: ${escapedWithHtmlUtils}</a></p>

<script type="text/javascript">
    function clicked(text){
        console.log(text);
    }
</script>

如果我在浏览器中按下CTRL+U以查看页面的来源,我会看到以下内容:

<p><a onClick="clicked('Any'String');" href="#">stringWithApostrophe: Any'String</a></p>
<p><a onClick="clicked('Any&#39;String');" href="#">escapedWithHtmlUtils: Any&#39;String</a></p>

...看起来不错,呈现如下:

浏览器渲染的html截图

...这也是我所期望的。当我单击第一个链接时,它也按预期失败,浏览器控制台显示错误消息Syntax error: missing ) after argument list,因为未转义的撇号破坏了 javascript 代码。

但是,虽然我预计第二个链接可以工作,但它也失败了,并显示相同的错误消息。为什么会这样?我无法理解,撇号如图CTRL+U 所示被转换为 html 实体,因此它不应该破坏 javascript。我一直在互联网上寻找可能的原因,但一无所获。我错过了什么?

更新:我已经将我用来重现错误的示例项目上传到 Github,以防它有用。

标签: javascriptjavahtmlspringescaping

解决方案


如您的问题所述,撇号已成功通过 HtmlUtils 类转换为 HTML 实体引用,变为&#39;. 您描述的行为正在发生,因为 HTML 解析器在将内容传递给 JavaScript 引擎之前解析属性值中的实体引用。onclick(...)因此,语句中的实体被解码为原始字符',如下所示。

onClick="clicked('Any&#39;String');"=> onClick="clicked('Any'String');"

因此对于 JS 引擎来说,这两个onClick(...)语句是等价的。

有关该问题的更多信息,请参阅此相关讨论讨论。


推荐阅读