Taming Thymeleaf update for Thymeleaf 3.1.2

Posted at — Oct 19, 2023
Taming Thymeleaf cover
Interested in learning more about Thymeleaf? Check out my book Taming Thymeleaf. The book combines all of my Thymeleaf knowledge into an easy to follow step-by-step guide.

Thymeleaf 3.1.2 was released recently and is inluded in Spring Boot 3.0.10 and 3.1.3. For security reasons, it is no longer allowed for a Thymeleaf template to directly access org.springframework.web.servlet.support.ServletUriComponentsBuilder.

This was used in my Taming Thymeleaf book to build a generic fragment that can be used for pagination controls.

If you still use it, you get this exception while running the application:

org.springframework.expression.EvaluationException:
Access is forbidden for type 'org.springframework.web.servlet.support.ServletUriComponentsBuilder' in this expression context.

The way to fix this is exposing the ServletUriComponentsBuilder as a Spring bean using @RequestScope:

com.tamingthymeleaf.application.infrastructure.web.WebMvcConfiguration
    @Bean
    @RequestScope
    public ServletUriComponentsBuilder urlBuilder() {
        return ServletUriComponentsBuilder.fromCurrentRequest();
    }

You can now replace urlBuilder.fromCurrentRequest() with @urlBuilder in the template itself.

To view the changes in context, check out this commit on GitHub.

Conclusion

Using Thymeleaf 3.1.2 needs a small change to the demo application of Taming Thymeleaf, but should be easy to apply given the above explanation.

If you have any questions or remarks, feel free to post a comment at GitHub discussions.

If you want to be notified in the future about new articles, as well as other interesting things I'm working on, join my mailing list!
I send emails quite infrequently, and will never share your email address with anyone else.