Spring Boot FreeMarker tutorial

In Spring Boot FreeMarker tutorial we are going to create a simple Spring Boot web application with FreeMarker template engine and H2 database.

Spring is a popular Java application framework. Spring Boot is an effort to create stand-alone, production-grade Spring based applications without musch hassle.

H2 is an open source relational database management system created entirely in Java. It can be embedded in Java applications or run in the client-server mode. It is easy to deploy and install and has small footprint.

FreeMarker is a server-side Java template engine for both web and standalone environments. Templates are written in the FreeMarker Template Language (FTL), which is a simple, specialized language.

$ tree
.
├── pom.xml
└── src
    └── main
        ├── java
        │   └── com
        │        └── zetcode
        │           ├── Application.java
        │           ├── bean
        │           │   └── City.java
        │           ├── controller
        │           │   └── MyController.java
        │           └── service
        │               ├── CityService.java
        │               └── ICityService.java
        └── resources
            ├── application.yml
            ├── data-h2.sql
            ├── schema-h2.sql
            ├── static
            │   └── css
            │       └── style.css
            └── templates
                ├── index.ftl
                └── showCities.ftl

This is the project structure. FreeMarker template files have .ftl suffix; they are located in the src/main/resources/template directory by default. Spring Boot automatically configures FreeMarker when it finds the dependency in the Maven POM file.

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">
    
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.zetcode</groupId>
    <artifactId>SpringBootFreemarker</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.3.RELEASE</version>
    </parent>    
    
    <dependencies>
        
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>                        
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>    
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>         

    </dependencies>    

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>            
        </plugins>
    </build>    
</project>

This is the Maven build file. The spring-boot-devtools enables hot swapping, disables template cache and enables live reloading. The spring-boot-starter-freemarker is starter for building Spring MVC applications with FreeMarker. The spring-boot-starter-jdbc is a starter for using JDBC in Spring Boot.

City.java
package com.zetcode.bean;

public class City {

    private Long id;
    private String name;
    private int population;

    public City() {
    }

    public City(Long id, String name, int population) {
        this.id = id;
        this.name = name;
        this.population = population;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPopulation() {
        return population;
    }

    public void setPopulation(int population) {
        this.population = population;
    }

    @Override
    public String toString() {
        return "City{" + "id=" + id + ", name=" + name + 
                ", population=" + population + '}';
    }
}

This is City bean class. It contains item id, name, and population.

application.yml
server:
    context-path: /cities

spring: 
    main:
        banner-mode: "off"       
    datasource:
        platform: h2

logging: 
    level: 
        org: 
            springframework: ERROR

The application.yml is the main Spring Boot configuration file. The context-path defines the name of the web application. With the banner-mode property we turn off the Spring banner. The platform value is used in SQL initialization scripts: schema-${platform}.sql and data-${platform}.sql. Also, we set the logging level for spring framework to ERROR.

Notice that we do not configure the datasource; Spring automatically configures H2 in the in-memory mode if there is no configuration data. We wanted to have an in-memory database, so we leave Spring to do the automatic configuration.

schema-h2.sql
CREATE TABLE CITIES(ID BIGINT PRIMARY KEY AUTO_INCREMENT, 
                  NAME VARCHAR(30), POPULATION BIGINT);

This SQL script creates the CITIES table.

data-h2.sql
INSERT INTO CITIES(NAME, POPULATION) VALUES('Bratislava', 432000);
INSERT INTO CITIES(NAME, POPULATION) VALUES('Budapest', 1759000);
INSERT INTO CITIES(NAME, POPULATION) VALUES('Prague', 1280000);
INSERT INTO CITIES(NAME, POPULATION) VALUES('Warsaw', 1748000);
INSERT INTO CITIES(NAME, POPULATION) VALUES('Los Angeles', 3971000);
INSERT INTO CITIES(NAME, POPULATION) VALUES('New York', 8550000);
INSERT INTO CITIES(NAME, POPULATION) VALUES('Edinburgh', 464000);
INSERT INTO CITIES(NAME, POPULATION) VALUES('Berlin', 3671000);

This script fills the table with data. Both scripts are located in the root of the classpath.

ICityService.java
package com.zetcode.service;

import com.zetcode.bean.City;
import java.util.List;

public interface ICityService {

    public List<City> findAll();
}

ICityService provides a contract method to get all cities from the data source.

CityService.java
package com.zetcode.service;

import com.zetcode.bean.City;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

@Service
public class CityService implements ICityService {

    @Autowired
    private JdbcTemplate jtm;

    @Override
    public List<City> findAll() {

        String sql = "SELECT * FROM CITIES";

        List<City> cities = jtm.query(sql, new BeanPropertyRowMapper(City.class));

        return cities;
    }
}

CityService contains the implementation of the findAll() method. We retrieve all cities from the CITIES table with the help of the JdbcTemplate.

@Autowired
private JdbcTemplate jtm;

JdbcTemplate is injected.

String sql = "SELECT * FROM CITIES";

This is SQL to be executed. We select all cities from the CITIES table.

List<City> cities = jtm.query(sql, new BeanPropertyRowMapper(City.class));

BeanPropertyRowMapper converts a row into a new instance of the specified mapped target class.

MyController.java
package com.zetcode.controller;

import com.zetcode.bean.City;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.zetcode.service.ICityService;

@Controller
public class MyController {

    @Autowired
    private ICityService cityService;
    
    @RequestMapping("/")
    public String index(Model model) {
        
        return "index";
    }    

    @RequestMapping("/showCities")
    public ModelAndView showCities() {

        List<City> cities = cityService.findAll();

        Map<String, Object> params = new HashMap<>();
        params.put("cities", cities);

        return new ModelAndView("showCities", params);
    }
}

This is the controller class for the Spring Boot web application. A controller is decorated with the @Controller annotation. The controller has two mappings: one mapping for the home page and one for listing all cities. Spring Boot automatically configures FreeMarker views when it detects FreeMarker starter in the Maven POM file.

@Autowired
private ICityService cityService;

We inject the ICityService into the field with the @Autowired annotation.

@RequestMapping("/")
public String index(Model model) {
    
    return "index";
}   

The "index" is the name of the view located in the predefined template directory.

@RequestMapping("/showCities")
public ModelAndView showCities() {

    List<City> cities = cityService.findAll();

    Map<String, Object> params = new HashMap<>();
    params.put("cities", cities);

    return new ModelAndView("showCities", params);
}

This controller method serves a list of cities. We find all city objects from the city service and place the resulting list into the parameters. Spring will locate the FreeMarker view named showCities and let the engine join the template with the model data.

style.css
h2 {color: blue}

td:nth-child(3) {
    text-align: right;
}

The style.css is a static file located in the src/main/resources/static/css directory. It sets the H2 tag to blue colour and right aligns the data of the third column.

index.ftl
<!DOCTYPE html>
<html>
    <head>
        <title>Home page</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <a href="showCities">Show cities</a>
    </body>
</html>

The index.ftl template file is the home page of the application. It contains a link to retrieve all cities.

showCities.ftl
<!DOCTYPE html>
<html>
    <head>
        <title>Cities</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="css/style.css" />
        </head>
    <body>
        <h2>List of cities</h2>
        
        <table>
            <tr>
                <th>Id</th>  
                <th>Name</th>  
                <th>Population</th>
            </tr>        

            <#list cities as city>
                <tr>
                    <td>${city.id}</td> 
                    <td>${city.name}</td> 
                    <td>${city.population}</td>
                </tr>
            </#list>        
        </table>                
    </body>
</html>

The showCities.ftl is a FreeMarker template file that contains placeholders to be filled with data from the model. To access the data, we use the ${} variable expressions.

<link rel="stylesheet" href="css/style.css" />

We include the static CSS file.

<#list cities as city>
    <tr>
        <td>${city.id}</td> 
        <td>${city.name}</td> 
        <td>${city.population}</td>
    </tr>
</#list>   

We iterate over the list of cities and put each city details into one table row. The #list directive is used to list a collection of data.

Application.java
package com.zetcode;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

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

We set up the Spring Boot application. The @SpringBootApplication annotation enables auto-configuration and component scanning.

Listing cities
Figure: Listing cities

The application is deployed on the built-in Tomcat server, which listens on port 8080.

In this tutorial, we have created a Spring Boot web application with FreeMarker and H2. You might also be interested in the related tutorials: Spring Boot Thymeleaf tutorial, Spring Boot Mustache tutorial, Spring Boot Swing integration tutorial, Introduction to Spring web applications, Standalone Spring applications, FreeMarker tutorial, Java tutorial, Introduction to Play, or Introduction to Stripes.