Generic Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

1. Introduction

Thymeleaf is a Java template engine for processing and creating HTML, XML, JavaScript, CSS, and text.

In this article, we will discuss how to use Thymeleaf with Spring along with some basic use cases in the view layer of a Spring MVC application.

The library is extremely extensible and its natural templating capability ensures templates can be prototyped without a back-end – which makes development very fast when compared with other popular template engines such as JSP.

2. Integrating Thymeleaf With Spring

Firstly let us see the configurations required to integrate with Spring. The thymeleaf-spring library is required for the integration.

Add the following dependencies to your Maven POM file:

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>3.0.11.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
    <version>3.0.11.RELEASE</version>
</dependency>

Note that, for a Spring 4 project, the thymeleaf-spring4 library must be used instead of thymeleaf-spring5.

The SpringTemplateEngine class performs all of the configuration steps. You can configure this class as a bean in the Java configuration file:

@Bean
@Description("Thymeleaf Template Resolver")
public ServletContextTemplateResolver templateResolver() {
    ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
    templateResolver.setPrefix("/WEB-INF/views/");
    templateResolver.setSuffix(".html");
    templateResolver.setTemplateMode("HTML5");

    return templateResolver;
}

@Bean
@Description("Thymeleaf Template Engine")
public SpringTemplateEngine templateEngine() {
    SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    templateEngine.setTemplateResolver(templateResolver());
    templateEngine.setTemplateEngineMessageSource(messageSource());
    return templateEngine;
}

The templateResolver bean properties prefix and suffix indicate the location of the view pages within the webapp directory and their filename extension, respectively.

The ViewResolver interface in Spring MVC maps the view names returned by a controller to actual view objects. ThymeleafViewResolver implements the ViewResolver interface and is used to determine which Thymeleaf views to render, given a view name.

The final step in the integration is to add the ThymeleafViewResolver as a bean:

@Bean
@Description("Thymeleaf View Resolver")
public ThymeleafViewResolver viewResolver() {
    ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
    viewResolver.setTemplateEngine(templateEngine());
    viewResolver.setOrder(1);
    return viewResolver;
}

3. Thymeleaf in Spring Boot

Spring Boot provides auto-configuration for Thymeleaf by adding the spring-boot-starter-thymeleaf dependency:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
    <version>2.3.3.RELEASE</version>
</dependency>

No explicit configuration is necessary. By default, HTML files should be placed in the resources/templates location.

4. Displaying Values from Message Source (Property Files)

The th:text=”#{key}” tag attribute can be used to display values from property files. For this to work the property file must be configured as messageSource bean:

@Bean
@Description("Spring Message Resolver")
public ResourceBundleMessageSource messageSource() {
    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
    messageSource.setBasename("messages");
    return messageSource;
}

Here is the Thymeleaf HTML code to display the value associated with the key welcome.message:

<span th:text="#{welcome.message}" />

5. Displaying Model Attributes

5.1. Simple Attributes

The th:text=”${attributename}” tag attribute can be used to display the value of model attributes. Let's add a model attribute with the name serverTime in the controller class:

model.addAttribute("serverTime", dateFormat.format(new Date()));

The HTML code to display the value of serverTime attribute:

Current time is <span th:text="${serverTime}" />

5.2. Collection Attributes

If the model attribute is a collection of objects, the th:each tag attribute can be used to iterate over it. Let's define a Student model class with two fields, id, and name:

public class Student implements Serializable {
    private Integer id;
    private String name;
    // standard getters and setters
}

Now we will add a list of students as model attribute in the controller class:

List<Student> students = new ArrayList<Student>();
// logic to build student data
model.addAttribute("students", students);

Finally, we can use Thymeleaf template code to iterate over the list of students and display all field values:

<tbody>
    <tr th:each="student: ${students}">
        <td th:text="${student.id}" />
        <td th:text="${student.name}" />
    </tr>
</tbody>

6. Conditional Evaluation

6.1. if and unless

The th:if=”${condition}” attribute is used to display a section of the view if the condition is met. The th:unless=”${condition}” attribute is used to display a section of the view if the condition is not met.

Add a gender field to the Student model:

public class Student implements Serializable {
    private Integer id;
    private String name;
    private Character gender;
    
    // standard getters and setters
}

Suppose this field has two possible values (M or F) to indicate the student's gender. If we wish to display the words “Male” or “Female” instead of the single character, we could accomplish this by using the following Thymeleaf code:

<td>
    <span th:if="${student.gender} == 'M'" th:text="Male" /> 
    <span th:unless="${student.gender} == 'M'" th:text="Female" />
</td>

6.2. switch and case

The th:switch and th:case attributes are used to display content conditionally using the switch statement structure.

The previous code could be rewritten using the th:switch and th:case attributes:

<td th:switch="${student.gender}">
    <span th:case="'M'" th:text="Male" /> 
    <span th:case="'F'" th:text="Female" />
</td>

7. Handling User Input

Form input can be handled using the th:action=”@{url}” and th:object=”${object}” attributes. The th:action is used to provide the form action URL and th:object is used to specify an object to which the submitted form data will be bound. Individual fields are mapped using the th:field=”*{name}” attribute, where the name is the matching property of the object.

For the Student class, we can create an input form:

<form action="#" th:action="@{/saveStudent}" th:object="${student}" method="post">
    <table border="1">
        <tr>
            <td><label th:text="#{msg.id}" /></td>
            <td><input type="number" th:field="*{id}" /></td>
        </tr>
        <tr>
            <td><label th:text="#{msg.name}" /></td>
            <td><input type="text" th:field="*{name}" /></td>
        </tr>
        <tr>
            <td><input type="submit" value="Submit" /></td>
        </tr>
    </table>
</form>

In the above code, /saveStudent is the form action URL and a student is the object that holds the form data submitted.

The StudentController class handles the form submission:

@Controller
public class StudentController {
    @RequestMapping(value = "/saveStudent", method = RequestMethod.POST)
    public String saveStudent(@ModelAttribute Student student, BindingResult errors, Model model) {
        // logic to process input data
    }
}

In the code above, the @RequestMapping annotation maps the controller method with URL provided in the form. The annotated method saveStudent() performs the required processing for the submitted form. The @ModelAttribute annotation binds the form fields to the student object.

8. Displaying Validation Errors

The #fields.hasErrors() function can be used to check if a field has any validation errors. The #fields.errors() function can be used to display errors for a particular field. The field name is the input parameter for both these functions.

HTML code to iterate and display the errors for each of the fields in the form:

<ul>
    <li th:each="err : ${#fields.errors('id')}" th:text="${err}" />
    <li th:each="err : ${#fields.errors('name')}" th:text="${err}" />
</ul>

Instead of field name the above functions accept the wild card character * or the constant all to indicate all fields. The th:each attribute is used to iterate the multiple errors that may be present for each of the fields.

The previous HTML code re-written using the wildcard *:

<ul>
    <li th:each="err : ${#fields.errors('*')}" th:text="${err}" />
</ul>

or using the constant all:

<ul>
    <li th:each="err : ${#fields.errors('all')}" th:text="${err}" />
</ul>

Similarly, global errors in Spring can be displayed using the global constant.

The HTML code to display global errors:

<ul>
    <li th:each="err : ${#fields.errors('global')}" th:text="${err}" />
</ul>

The th:errors attribute can also be used to display error messages. The previous code to display errors in the form can be re-written using th:errors attribute:

<ul>
    <li th:errors="*{id}" />
    <li th:errors="*{name}" />
</ul>

9. Using Conversions

The double bracket syntax {{}} is used to format data for display. This makes use of the formatters configured for that type of field in the conversionService bean of the context file.

The name field in the Student class is formatted:

<tr th:each="student: ${students}">
    <td th:text="${{student.name}}" />
</tr>

The above code uses the NameFormatter class, configured by overriding the addFormatters() method from the WebMvcConfigurer interface. For this purpose, our @Configuration class overrides the WebMvcConfigurerAdapter class:

@Configuration
public class WebMVCConfig extends WebMvcConfigurerAdapter {
    // ...
    @Override
    @Description("Custom Conversion Service")
    public void addFormatters(FormatterRegistry registry) {
        registry.addFormatter(new NameFormatter());
    }
}

The NameFormatter class implements the Spring Formatter interface.

The #conversions utility can also be used to convert objects for display. The syntax for the utility function is #conversions.convert(Object, Class) where Object is converted to Class type.

To display student object percentage field with the fractional part removed:

<tr th:each="student: ${students}">
    <td th:text="${#conversions.convert(student.percentage, 'Integer')}" />
</tr>

10. Conclusion

In this tutorial, we've seen how to integrate and use Thymeleaf in a Spring MVC application.

We have also seen examples of how to display fields, accept input, display validation errors, and convert data for display. A working version of the code shown in this article is available in a GitHub repository.

Generic bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE
14 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Comments are closed on this article!