是否可以从Thymeleaf文本模板调用静态方法?
官方指南提到应该可以调用这样的方法:
<p th:text="${@myapp.translator.Translator@translateToFrench(textVar)}">Some text here...</p>
当我试图在文本模板中使用它时(TemplateResolver的模式被设置为TemplateMode.TEXT),我得到了一个异常:
org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating OGNL expression: "@java.lang.System@currentTimeMillis()" (template: "template.txt" - line 1, col 18)
下面是我的示例模板:
System millis: [(${@java.lang.System@currentTimeMillis()})]
在搜索了一段时间之后,我还发现了这种形式的调用方法:
System millis: [(${T(java.lang.System).currentTimeMillis()})]
同样的错误会失败。
我需要做的是允许从模板中使用自定义数字格式化程序类( #numbers
实用程序对象的功能不足以满足我的情况)。通过将非静态类作为上下文变量提供如下所示,我可以调用非静态类上的方法:
Some value: [(${formatter.format(someValue)})]
但是,对于我来说,使用静态类更容易,而不需要显式地将其添加到每个模板的上下文中。
顺便说一句,我不使用春天,只是纯粹的Thymeleaf。
更新
我应该花更多的时间来分析Thymeleaf异常的堆栈跟踪。事实证明,这种行为的根本原因是org.thymeleaf.exceptions.TemplateProcessingException: Instantiation of new objects and access to static classes is forbidden in this context
异常,这是此更改的结果:https://github.com/thymeleaf/thymeleaf/issues/809
降级到Thymeleaf 3.0.11“修复”它。
现在,我正在寻找一个解决方案,以绕过这个新的撤销模式,在最新的Thymeleaf (3.0.12暂时)。我确信这在我的情况下是安全的,因为我是代码和模板的唯一作者。
发布于 2021-11-24 15:36:39
另一种选择是使用th:with
属性。它有点冗长,但仍然应该允许您具有相同的灵活性。(这在3.0.12.RELEASE
上适用于我。)
[# th:with="time=${@java.lang.System@currentTimeMillis()}"]System millis: [[${time}]][/]
https://stackoverflow.com/questions/70084468
复制相似问题