javascript - 使用 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'String');" href="#">escapedWithHtmlUtils: Any'String</a></p>
...看起来不错,呈现如下:
...这也是我所期望的。当我单击第一个链接时,它也按预期失败,浏览器控制台显示错误消息Syntax error: missing ) after argument list
,因为未转义的撇号破坏了 javascript 代码。
但是,虽然我预计第二个链接可以工作,但它也失败了,并显示相同的错误消息。为什么会这样?我无法理解,撇号如图CTRL+U
所示被转换为 html 实体,因此它不应该破坏 javascript。我一直在互联网上寻找可能的原因,但一无所获。我错过了什么?
更新:我已经将我用来重现错误的示例项目上传到 Github,以防它有用。
解决方案
如您的问题所述,撇号已成功通过 HtmlUtils 类转换为 HTML 实体引用,变为'
. 您描述的行为正在发生,因为 HTML 解析器在将内容传递给 JavaScript 引擎之前解析属性值中的实体引用。onclick(...)
因此,语句中的实体被解码为原始字符'
,如下所示。
onClick="clicked('Any'String');"
=> onClick="clicked('Any'String');"
。
因此对于 JS 引擎来说,这两个onClick(...)
语句是等价的。
有关该问题的更多信息,请参阅此相关讨论讨论。
推荐阅读
- python - Plotly Scattermapbox 文本字体系列不会改变
- windows - 后置 SQL 。当我使用 \i 从 sql 读取时,cmd 中的权限被拒绝
- ios - Swift DateFormatter 问题
- node.js - Mongoose,如何对集合中选定对象的日期进行排序
- json - (ObjectBox | Dart) 如何将 json 传递给实体类?
- macos - GitHub Actions:productsign 挂起
- javascript - html 元素数组或字符串 typescript
- javascript - Adding comments to video with jQuery
- python - 可以将列表更改应用于其他列表的功能
- java - 选择 webdriver 中包含文本的任何元素