FreeMarker is a java-based template engine, commonly used to generate dynamic mvc architecture web pages.

Add FreeMarker Dependency

Add FreeMarker dependency into pom.xml:

1
2
3
4
5
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
    <version>2.1.4.RELEASE</version>
</dependency>

Add Freemarker Properties

Add FreeMarker properties into application.properties:

1
2
3
4
5
6
7
8
spring.freemarker.settings.default_encoding=UTF-8
spring.freemarker.settings.datetime_format=dd/MM/yyyy HH:mm:ss
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html;charset=UTF-8
spring.freemarker.expose-request-attributes=true
spring.freemarker.expose-session-attributes=true
spring.freemarker.expose-spring-macro-helpers=true
spring.freemarker.suffix=.ftl

Create Freemarker Template

  • Right click resources/templates directory: New > File
  • Fill in: hello-freemarker.ftl
  • Click “OK” button
img

Copy and paste the following content into hello-freemarker.ftl:

1
2
3
4
5
6
7
<!DOCTYPE html>
<html>
    <head>
      <title>Hello FreeMarker</title>
    </head>
    <body>Hello Product: ${product.name}</body>
</html>

Create Freemarker Controller

  • Right click co.dongchen.shop.controller directory: New > Java Class
  • Fill in: FreeMarkerController
  • Click “OK” button
img

Copy and paste the following content into FreeMarkerController.java:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package co.dongchen.shop.controller;

import co.dongchen.shop.common.model.Product;
import co.dongchen.shop.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
public class FreeMarkerController {

    @Autowired
    private ProductService productService;

    @RequestMapping("hellofreemarker")
    public String helloFreeMarker(ModelMap modelMap) {
        List<Product> products = productService.getProducts();
        Product firstProduct = products.get(0);
        modelMap.put("product", firstProduct);
        return "hello-freemarker";
    }
}

Verify

Run the App

1
2
// Short Cut for "Run the Program"
Alt + Shift + F10
img

Choose the correspondent option and press enter.

View FreeMarker Template Page in the Browser

1
http://localhost:8080/hellofreemarker
img

References Apache FreeMarker

Buy me a coffeeBuy me a coffee