The new Certification Class of Learn Spring Security is out:

>> 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>2.1.4.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring4</artifactId>
    <version>2.1.4.RELEASE</version>
</dependency>

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

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. 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}" />

4. Displaying Model Attributes

4.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}" />

4.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>

5. Conditional Evaluation

5.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>

5.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>

6. 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.

7. 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>

8. 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>

9. 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.

Go deeper into Spring Security with the course:

>> LEARN SPRING SECURITY

Sort by:   newest | oldest | most voted
Hasan
Guest

Hi , Can I create inheritable pages using with Thymeleaf. For example, I can create main page in Apache Wicket or Angular js and then when I want to use it for sub pages, I can extend this main pages… Actually I want to learn that can I do same thing using Thymeleaf.

Eugen Paraschiv
Guest
Hey Hasan – I haven’t tried to do that, but I don’t think it’s easily doable. The idea with a template page is that it goes through a specific code path in Spring MVC, so if you’re just serving other types of assets (such as static assets), you can’t embed a Thymeleaf template there and expect to have that rendered. Now – that still depends on how you’re actually making the HTTP request, so it could potentially be done, just not necessarily easy. Finally, I’d recommend using Thymeleaf as your main driver and simply use Angular JS within the HTML… Read more »
JULIUS
Guest

Why don’t you specify which file to put registry.addFormatter(new NameFormatter());

Without that this whole article is useless.

Grzegorz Piwowarek
Guest

https://github.com/eugenp/tutorials/blob/master/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java

You can find it here along with the whole configuration. The method comes from the WebMvcConfigurer interface.

Naga A
Guest

How to display errors without th:object ? I am getting below error :
Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Could not bind form errors using expression “*”. Please check this expression is being executed inside the adequate context (e.g. a with a th:object attribute) (reset_password:70)

My code is :

Input is incorrect

Eugen Paraschiv
Guest

Looking into it Naga. Cheers,
Eugen.

Michał Aibin
Guest
Hi @naga_a:disqus, First of all. The error that you sent is not caused by our code example. Moreover, it is hard to reproduce your error, as you provided just a little piece of your code. I have a few guesses: a) Looks like you didn’t add any form into the modelAttribute inside the controller for this specific view. The error indicates, that there are no form fields, so there is no form added probably. b) There may be problem with the input inside the form I would try to access one field first and see if Thymeleaf can process your… Read more »
Naga A
Guest
Thanks. Please see my code below : @RequestMapping(“reset_password”) public String getResetPassword(Model model, HttpServletRequest request){ String key = request.getParameter(“key”); if(key == null){ key = (String)request.getSession().getAttribute(“resetPasswordKey”); } if(!””.equals(key)){ request.getSession().setAttribute(“resetPasswordKey”, key); Optional user = userRepository.findOneByResetKey(key); if(user == null || !user.isPresent()){ log.error(“Either key is expired or Invalid try.”); return “reset_password_error”; } } return “reset_password”; } @PostMapping(“/reset_password”) @Timed public String resetPassword(Model model, BindingResult bindingResult, HttpServletRequest request) { String resetKey = (String)request.getSession().getAttribute(“resetPasswordKey”); if(!””.equals(resetKey)){ Optional user = userRepository.findOneByResetKey(resetKey); if(user != null) { String password = request.getParameter(“password”); String confirmPassword = request.getParameter(“confirmPassword”); if(password == null || “”.equals(password.trim())){ bindingResult.reject(“password”, “Please enter password”); } if(confirmPassword == null || “”.equals(confirmPassword.trim())){ bindingResult.reject(“confirmPassword”, “Please… Read more »
Michał Aibin
Guest

You would be able to do it without th:object if you’ll create a form class, with all parameters and then you’ll add this to the model as an attribute.
There are a few minor issues with your code, I would recommend you to start with this article, before you’ll proceed with Thymeleaf:
http://www.baeldung.com/spring-requestmapping

Naga A
Guest

Thanks for reply. I have gone though this link. But still, it does not talk about how to add form errors and display errors without th:object.

Eugen Paraschiv
Guest

Hey Naga – let me jump in here with a quick note.
While I hope the discussion is useful, let’s actually move it over to Github (open an issue there); that way we keep the comments here at a more manageable level.
Also, if possible, try to edit your last comment – as it simply has to much code for the comment section here.
Thanks,
Eugen.

Naga A
Guest

Thanks for reply. I created the issue.
https://github.com/thymeleaf/thymeleaf-spring/issues/126

Eugen Paraschiv
Guest

Opening the issue on the official repo was an interesting choice. I assumed you were going to open it on our tutorials repo – the one that supports this article.

Cheers,
Eugen.

Naga A
Guest

oops. Next time I will do that. We got reply and they closed the issue.https://github.com/thymeleaf/thymeleaf-spring/issues/126.
We can display errors outside form so that we don’t need to use any object. I will try that.

wpDiscuz