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

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

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

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

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

@GetMapping("/pr/{name}")
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

src/main/resources/templates/steve.ftl

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

<!DOCTYPE html>
<html>
<head></head>
<body>

<h1>My name is ${name}</h1>

</body>
</html>