Spring Boot integrates FreeMarker instances

preface

In previous articles Spring Boot integrates Thymeleaf In, we learned how to integrate the template Thymeleaf into Spring Boot. Today, let's take a look at another old open source free template engine - FreeMarker!

Introduction to FreeMarker

FreeMarker is a template engine: a general tool based on templates and data to be changed and used to generate output text (HTML web pages, e-mail, configuration files, source code, etc.). It is not for end users, but a Java class library. It is a component that programmers can embed in the products they develop.

The above is the official definition from FreeMarker. By using FreeMarker, we can render the template and data we need into HTML, so as to achieve the effect we want. By separating templates from data, the division of labor is more clear. In terms of templates, we focus on how to display data, while in terms of data, we can focus on what kind of data to display. The following figure is the function of FreeMarker described above.

Next, let's take a look at how to integrate FreeMarker into our Spring Boot like Thymeleaf to make our development easier.

preparation

Environmental preparation

Before the official start, we still give the environment based on this paper to avoid the possible impact of environmental problems.

  • JDK 17 (theoretically recommended version no less than 1.8)
  • IDEA
  • SpringBoot 2.x

Add FreeMarker dependency

Before starting, we need to add related dependencies of FreeMarker. Similarly, here we can choose two methods. One is to add it when the project is created, and the other is to manually add it in the project pom.xml file after the project is created. Next, let's see how to add it in two different ways. If you don't know how to create a Spring Boot project, you can refer to my previous article: Three ways to create Spring Boot projects.

  1. First kind

When creating a new Spring Boot project using IDEA, check Apache FreeMarker in the template engine when adding dependencies.

2. The second

If the FreeMarker template engine dependency is not added at the time of creation, or there is no such requirement at the beginning of the project creation, but the requirement is added in the subsequent process, you can manually add the FreeMarker dependency in the project pom.xml.

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

Add FreeMarker related configuration

After adding dependencies, we need to add relevant configurations of FreeMarker in the project configuration file application.yml.

spring:
  freemarker:
    # Template suffix
    suffix: .ftl
    # Document type
    content-type: text/html
    # Page coding
    charset: UTF-8
    # Page cache
    cache: false
    # Template path
    template-loader-path: classpath:/templates/

Writing entity classes and controllers

Writing entity classes

Create a User class and complete its various setter s, getter s and construction methods. Here, I still use the Lombok plug-in to simplify our code. For more usage of this plug-in, please refer to my previous article: Lombok installation and use guide.

package com.cunyu.springbootfreemarkerdemo.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * Created with IntelliJ IDEA.
 *
 * @author : zhangliang
 * @version : 1.0
 * @project : java-learning
 * @package : com.cunyu.springbootfreemarkerdemo.entity
 * @className : User
 * @createTime : 2021/11/30 21:55
 * @email : 747731461@qq.com
 * @Official account: Village rain
 * @website : https://cunyu1943.github.io
 * @description :
 */

@Component
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int age;
    private String name;
    private String email;
}

Write Controller

Here, we create a User object, set its age, Email, name and other related information, and then add it to the attribute to facilitate transmission to the front end for display.

package com.cunyu.springbootfreemarkerdemo.controller;

import com.cunyu.springbootfreemarkerdemo.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

/**
 * Created with IntelliJ IDEA.
 *
 * @author : zhangliang
 * @version : 1.0
 * @project : java-learning
 * @package : com.cunyu.springbootfreemarkerdemo.controller
 * @className : UserController
 * @createTime : 2021/11/30 22:04
 * @email : 747731461@qq.com
 * @Official account: Village rain
 * @website : https://cunyu1943.github.io
 * @description :
 */
@Controller
public class UserController {
    @GetMapping("/index")
    public String index(Model model) {
        User user = new User();
        user.setAge(26);
        user.setEmail("747731461@qq.com");
        user.setName("Village Yuyao");
        model.addAttribute("user", user);
        return "index";
    }
}

Data rendering

After the entity class and Controller are written, we can use the template to display. We create a new index.ftl file in the resources/templates path of the project. Note that the file name here should be consistent with the string returned by the index method in the Controller.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>FreeMarker experiment</title>
</head>
<body>
    <table>
        <tr>
            <td>full name</td>
            <td>Age</td>
            <td>Email</td>
        </tr>
        <tr>
            <td>${user.name}</td>
            <td>${user.age}</td>
            <td>${user.email}</td>
        </tr>
    </table>
</body>
</html>

test

Start our project and access the following path in the browser:

http://localhost:8080/index

If the information shown in the figure below is displayed, it means that our integration work has been successfully completed!

summary

The above is the specific process of integrating FreeMarker with Spring Boot, which can be combined with the previous article: Spring Boot integrates Thymeleaf instances Read together and compare some similarities and differences between Thymeleaf and FreeMarker in the integration process. I believe you will gain more.

Finally, I have uploaded the case code of this article to Github. If you need it, you can get it yourself: Portal.

Tags: Java FreeMarker Spring Boot

Posted on Wed, 01 Dec 2021 20:13:16 -0500 by bfinucan