【技术】Thymeleaf JS 事件传参字符类型报错,只允许数值类型和布尔类型

Thymeleaf JS 事件传参字符类型报错,只允许数值类型和布尔类型

报错信息

不废话,先看错误,错误信息比较多,摘了核心部分。

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. (template: "/xxx" - line m, col n)
	at org.thymeleaf.standard.expression.SelectionVariableExpression.executeSelectionVariableExpression(SelectionVariableExpression.java:173) ~[thymeleaf-3.0.15.RELEASE.jar:3.0.15.RELEASE]
	at org.thymeleaf.standard.expression.SimpleExpression.executeSimple(SimpleExpression.java:92) ~[thymeleaf-3.0.15.RELEASE.jar:3.0.15.RELEASE]
	......

翻译过来是:

在此上下文中只允许返回数字或布尔值的变量表达式,在此表达式的上下文中不信任任何其他数据类型,包括字符串或任何其他可以呈现为文本文本的对象。一个典型的例子是事件处理程序的HTML属性(例如“onload”),其中来自变量的文本数据最好输出到“data-*”属性,然后从事件处理程序中读取。

代码

实体类信息如下:

@Data
public class Student extends BaseEntity{
    private String no;
    ......
}

HTML页面代码如下,错误的地方在编辑链接绑定点击事件的写法。

<tr th:each="stu,status:${pageInfo.list}" th:object="${stu}">
    <th><input type="checkbox"/> </th>
    ......
    <td>
        <a href="javascript:void(0)" th:onclick="|edit(*{no})|">编辑</a>
        <a href="#">删除</a>
    </td>
</tr>

问题分析解决

HTML 代码编辑链接中th:onclick="|edit(*{no})|"中的竖线是对字符类型操作,可以理解为拼接。通过查资料,问题出现的原因是 Thymeleaf 在对字符操作时容易出现注入安全问题(类似 SQL 注入),所以在模板解析时只允许数值类型和布尔类型。那如何解决问题呢?既然是因为字符类型拼接导致的,那不拼接就可以了。

<a href="javascript:void(0)" th:onclick="edit([[*{no}]])">编辑</a>

以上写法是比较推荐的简单写法。.

另外在报错信息里也提供了一种方案,使用th:data-*给标签添加一个data-*的自定义属性,在 JS 脚本中使用this.getAttribute('data-*')获取自定义属性的值。其中 JS 中的 this 代表当前超链接元素。

<a href="javascript:void(0)" th:data-no="*{no}" th:onclick="edit(this.getAttribute('data-no'))">编辑</a>

以上纯属个人理解,如有疑问不妥的地方欢迎指正。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值