Close

Spring Boot - Using FreeMarker View

[Last Updated: Jan 6, 2018]

To use FreeMarker in Spring Boot application, we just need to include spring-boot-starter-freemarker dependency and place the template file under src/main/resources/templates/ directory (the default location for all template engines in Spring Boot application). The rest of the configurations is done automatically by Spring Boot. Also check out our FreeMarker example with plain MVC to know what are those other configurations.

Example

Maven dependencies

pom.xml

<project .....>
<modelVersion>4.0.0</modelVersion>
<groupId>com.logicbig.example</groupId>
<artifactId>spring-boot-freemarker-example</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

Note that spring-boot-starter-freemarker will pull all freemarker related dependencies and Spring Web MVC dependencies as well.

FreeMarker Template File

/src/main/resources/templates/my-page.ftl

<!DOCTYPE html>
<html lang="en">
<body>
<h2>FreeMarker View</h3>
	<div> Message: ${msg}</div>
	<div> Time: ${time} </div>
</body>
</html>

Spring MVC Controller

@Controller
@RequestMapping("/")
public class MyController {
  
  @RequestMapping
  public String handleRequest (Model model) {
      model.addAttribute("msg", "A message from the controller");
      model.addAttribute("time", LocalTime.now());
      return "my-page";
  }
}

Spring boot main class

@SpringBootApplication
public class ExampleMain {

  public static void main(String[] args) throws InterruptedException {
      SpringApplication.run(ExampleMain.class, args);
  }
}

To try examples, run spring-boot maven plugin (configured in pom.xml of example project below):

mvn spring-boot:run

We can also run the main class from our IDE.

Output

We can also deploy FreeMarker project (or other template based projects) to a servlet container as war. Check out this example.

Example Project

Dependencies and Technologies Used:

  • Spring Boot 1.5.9.RELEASE
    Corresponding Spring Version 4.3.13.RELEASE
  • spring-boot-starter-freemarker : Starter for building MVC web applications using FreeMarker views.
  • JDK 1.8
  • Maven 3.3.9

Spring Boot - FreeMarker View Example Select All Download
  • spring-boot-freemarker-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • resources
          • templates
            • my-page.ftl

    See Also