Using Thymeleaf in Spring MVC

Thymeleaf is an open template engine with the ability to handle many other languages such as HTML, XML, Javascript, CSS. Users can use it to customize the template according to their needs. In this tutorial, I will guide you all some basic steps to use Thymeleaf in your Spring MVC application.

First, I will create a new Maven project as an example:

Using Thymeleaf in Spring MVC

If you do not know how to create Spring MVC project, just refer to this tutorial. Here, I edited the version of the dependencies as follows:

To use Thymeleaf, we need to add its dependencies:

To run this example, I will use Maven Jetty Plugin:

Before I start on the subject of this tutorial, I want to talk to you a little bit about the dialect concept in Thymeleaf …

As I said, Thymeleaf allows us to customize our template easily. This customization will use the objects specified by Thymeleaf. We will have logical processing in these objects so these objects also known as processors and set of processor objects called a dialect.

By default, Thymeleaf provides us with two dialects: one is Standard Dialect and another one is SpringStandard Dialect with some support for the Spring framework. In this tutorial, we will use the SpringStandard Dialect.

To use Thymeleaf in Spring MVC, we first need to declare Thymeleaf’s SpringTemplateEngine object in the Spring container. This object will help us declare Thymeleaf’s ViewResolver with Spring.

Let’s open the servlet-context.xml file located in the /src/main/webapp/WEB-INF/spring/appServlet directory, removing the default viewResolver:

then add the declaration of Thymeleaf’s SpringTemplateEngine object:

As you can see, to declare Thymeleaf’s SpringTemplateEngine object in the Spring container, we have to declare another object called SpringResourceTemplateResolver to configure the location of the template files. And the ThymeleafViewResolver object will use this TemplateEngine object.

The configuration of the SpringResourceTemplateResolver is similar to the InternalResourceViewResolver object, the only difference being that we will work on .html files, not .jsp files anymore. That’s a better template since in the .jsp file we can declare the Java code in it.

Now, I will rename the home.jsp file located in /src/main/webapp/WEB-INF/views/ to home.html for using with Thymeleaf. The contents of the home.html file are now as follows:

By using Thymeleaf’s namespace, I will edit the contents of the home.html file as follows:

As you can see, here I have declared Thymeleaf’s namespace and used it as an attribute of HTML tag.

The result is the same when you run with InternalResourceViewResolver:

Using Thymeleaf in Spring MVC

Add Comment