Spring Boot 2.4.2 和 Thymeleaf 3.0.12 - 访问静态方法

chr*_*oph 9 thymeleaf spring-boot

自从我切换到Spring Boot 2.4.2我的Thymeleaf模板就坏了。当我想访问 Spring Controller 中的静态成员时,出现以下错误:

异常处理模板“template_name”:在此上下文中禁止实例化新对象和访问静态类。

代码如下: th:text="${T(com.test).testMethod("1234")}"

你有什么建议来解决这个问题吗?

Sla*_*nov 10

此更改是Thymeleaf 3.0.12的一部分。它们通过限制对静态代码的访问(OGNL 中的@identifier@,SpringEL 中的 T(identifier))来提高受限表达式评估模式的安全性。他们自己做了什么?...“避免了新对象的实例化和对静态类的调用”,如发行说明中所述。您可以将 JAVA 调用移动到您的控制器中并将结果放入视图模型中。从 Thymeleaf 模板访问此变量后。


RiZ*_*KiT 10

另一个快速解决方法是使用 th:with

th:text="${testText}"
th:with="testText=${T(com.test).testMethod("1234")}"
Run Code Online (Sandbox Code Playgroud)

来源/荣誉:https://github.com/thymeleaf/thymeleaf/issues/816#issuecomment-791921248https://github.com/thymeleaf/thymeleaf/issues/816#issuecomment-826401631


mic*_*czy 5

有一种解决方法可以使用在 Spring 应用程序上下文中通过 @beanName 语法注册的 bean 中的方法。像这样:

<div th:text="${@testService.testMethod('123')}">...</div>
Run Code Online (Sandbox Code Playgroud)

http://www.thymeleaf.org/doc/articles/springmvcaccessdata.html