Since I switched to Spring Boot 2.4.2
my Thymeleaf
templates are broken. When I want to access a static member in Spring Controller I get the following error:
Exception processing template "template_name": Instantiation of new objects and access to static classes is forbidden in this context.
The code looks like:
th:text="${T(com.test).testMethod("1234")}"
Do you have any recommendation to fix this?
You will have to follow the below steps to create a web application in Spring Boot by using Thymeleaf. Use the following code to create a @Controller class file to redirect the Request URI to HTML file − In the above example, the request URI is /index, and the control is redirected into the index.html file.
It contains 6 types of templates as given below − All templates, except Legacy HTML5, are referring to well-formed valid XML files. Legacy HTML5 allows us to render the HTML5 tags in web page including not closed tags. You can use Thymeleaf templates to create a web application in Spring Boot.
In Thymeleaf, these model attributes (or context variables in Thymeleaf jargon) can be accessed with the following syntax: $ {attributeName}, where attributeName in our case is messages. This is a Spring EL expression.
Spring beans. Thymeleaf allows accessing beans registered at the Spring Application Context with the @beanName syntax, for example: In the above example, @urlService refers to a Spring Bean registered at your context, e.g. This is fairly easy and useful in some scenarios.
Another quick fix is the use of th:with
th:text="${testText}"
th:with="testText=${T(com.test).testMethod("1234")}"
Source/Kudos: https://github.com/thymeleaf/thymeleaf/issues/816#issuecomment-791921248 and https://github.com/thymeleaf/thymeleaf/issues/816#issuecomment-826401631
There is a workaround to use method from beans registered at the Spring Application Context with the @beanName syntax. Like this:
<div th:text="${@testService.testMethod('123')}">...</div>
http://www.thymeleaf.org/doc/articles/springmvcaccessdata.html
This change is the part of Thymeleaf 3.0.12. They improve restricted expression evaluation mode security by restriction of the access to static code (@identifier@ in OGNL, T(identifier) in SpringEL). What they have done by themselves? ... "Avoided instantiation of new objects and calls to static classes" as stated in release notes. You may move the JAVA calls into your controller and put the result into the view model. After just access this variable from Thymeleaf template.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With