Changing Spring MVC to use Freemarker templates in the ViewResolver

By Steve Claridge on 2017-11-16.

By default Spring MVC uses Thymeleaf as its View Resolver but I prefer Freemarker. So this short tutorial shows how to switch Spring from using Thymeleaf to Freemarker templates.

The code examples were created using Spring Boot 1.5.8.

If you already have a Spring MVC project up and running using the default Tymeleaf setup then there is hardly anything you need to change for Freemarker. Templates are stored in the same place, the controllers behaves in the same way and the view is returned in the same way. The change is essentially adding a Maven dependency for Freemarker.

So, add this Maven dependency to your pom.xml


If you already have Thymeleaf explicitly defined in your POM then you need to remove it, but it is likely you will not as Spring's Web dependency include Thymeleaf anyway. So if the below is in your POM, get rid of it


The only other thing that differs between Thymeleaf and Freemarker is the default template file extension that Spring expects and looks for, Thymeleaf uses .html and Freemarker uses .ftl.

Here's an example Controller method to return a view from a template

public String pr( @PathVariable(value="name") String name, Model model )
   model.addAttribute( "name", name );
   return "steve";

Spring will attempt to load the following template file using the Freemarker ViewResolver


My example template looks like this, just displays the name passed in the model.

<!DOCTYPE html>
<body> <h1>My name is ${name}</h1> </body>