首页 > 解决方案 > 在此上下文中仅允许返回数字或布尔值的变量表达式

问题描述

我正在尝试将一个值传递给我的 javascript 函数,但该函数调用取决于一个布尔变量。在我最近升级到 thymeleaf security 5 之前,我的工作正常。

这是代码片段。

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

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. 

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

标签: javascripthtmlspringspring-bootthymeleaf

解决方案


从 Thymeleaf 3.0.10 开始,他们修复了一个关于未转义代码的安全漏洞。

尝试

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

或者推荐的方式:

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

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


推荐阅读