Accessing the Database from a Thymeleaf Template

Accessing the Database from a Thymeleaf Template

This week, I had a student ask me how they could use a Java function to access the database from a Thymeleaf template. Thymeleaf is a modern templating engine. And accessing the database directly from Thymeleaf is certainly something you could do. But is it really something you want to do?

I’ve worked for a couple major retailers which had JSP templates accessing the database with static Java methods. It was not a good thing.

When you’re using Thymeleaf with Spring MVC, you’re following the MVC design pattern. MVC is Model, View, Controller. The Thymeleaf template is the ‘View’. The Spring controller will return a model to the Thymeleaf template engine. The model should be a data structure. Nothing more.