在此上下文中只允许返回数字或布尔值的变量表达式

Kni*_*der 12 html javascript spring thymeleaf spring-boot

我试图将值传递给我的javascript函数,但该函数调用依赖于布尔变量.在我最近升级到百日咳安全5之前,我一直工作得很好.

这是代码段.

<body th:onload="${timerEnabled} ? 'javascript:runTimer(\'' + ${timeRemaining} + '\');'">
Run Code Online (Sandbox Code Playgroud)

对于要完成的函数调用,timerEnabled必须为true,但是thymeleaf现在会抛出异常

org.thymeleaf.exceptions.TemplateProcessingException: Only variable expressions returning numbers or booleans are allowed in this context, any other datatypes are not trusted in the context of this expression, including Strings or any other object that could be rendered as a text literal. A typical case is HTML attributes for event handlers (e.g. "onload"), in which textual data from variables should better be output to "data-*" attributes and then read from the event handler. 
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?谢谢.

leo*_*ome 18

自Thymeleaf 3.0.10以来,他们修复了一个关于非转义代码的安全漏洞.

尝试

<body th:onload="[[${timerEnabled}]] ? 'javascript:runTimer(\'' + 
[[${timeRemaining}]] + '\');'">
Run Code Online (Sandbox Code Playgroud)

或者推荐的方式:

<body th:data1="${timerEnabled}"
  th:data2="${timeRemaining}"
    th:onload="this.getAttribute('data1') ? javascript:runTimer(this.getAttribute('data2'));">
Run Code Online (Sandbox Code Playgroud)

阅读更多内容:https://github.com/thymeleaf/thymeleaf/issues/707 并且:http: //forum.thymeleaf.org/Thymeleaf-3-0-10-JUST-PUBLISHED-tt4031348.html#a4031353


Kni*_*der 1

我能够通过使用这种方法让它工作

<body>

<script th:inline="javascript">
    /*<![CDATA[*/

    var flag = [[${timerEnabled}]]; // if timer should be included or not
    var timeRemaining = [[${timeRemaining}]]; // the time remaining.
    window.onload = function() {
        if(!flag)
            return; // Exit/Return if the variable is false
        runTimer(timeRemaining); // Call your favourite method if the variable is true
    };

    /*]]>*/
</script>
Run Code Online (Sandbox Code Playgroud)

任何其他方法(例如例外中建议的方法)都值得赞赏。