代码之家  ›  专栏  ›  技术社区  ›  joanlofe

用Spring转义HTML中的撇号

  •  3
  • joanlofe  · 技术社区  · 6 年前

    我在一些遗留代码中有一个错误,在试图修复它时,我发现了一个我不理解的行为。该应用程序是一个使用JSP和JSTL的SpringMVC应用程序。下面是一个简单的例子,它再现了我所说的行为。我的控制器的代码是:

    @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>
    

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

    screenshot of html rendered by browser

    Syntax error: missing ) after argument list 因为未替换的撇号破坏了javascript代码。

    但是,虽然我期待第二个环节能起作用,, . 为什么会这样?我不能理解它,撇号被转换成html实体

    使现代化 :我上传了 the example project 我曾经将错误复制到Github,以防它有用。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Tatenda Zifudzi    6 年前

    正如您在问题中提到的,HtmlTils类成功地将撇号转换为HTML实体引用,从而成为 &#39; onclick(...) 语句因此被解码为原始字符 ' 如下图所示。

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

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

    this related discussion 讨论以获取有关该问题的更多信息。