Spring Boot integrates freemarker template engine

This article is participating in the "Golden Stone Project. Share 60,000 cash prize"

foreword

The field of J2EE includes five major engines, namely template engine, process engine, search engine, rule engine, and report engine. Each engine can solve a certain problem. The template engine solves the separation of user interface and business data. The process engine solves the problem of driving the business to execute according to a certain process. The difference is that different business decisions need to be separated from the code. Regarding these engine technologies, we will focus on explaining them one by one in subsequent articles.

picture.png

This article will explain the template engine. The template engines commonly used in J2EE include Velocity, Freemark, Thymeleaf, etc. Since the Velocity template engine is no longer supported after Spring Boot2.0, this article focuses on the Freemar template engine.

Introduction

FreeMarker is a template engine written in the Java language that generates text output based on templates. Separate the display of business data and user interface, and focus on the rendering of views, thereby improving efficiency.

Application Scenario

  • view rendering
  • Make templates, such as email templates, SMS templates, etc.
  • Code generators, such as mybatis-plus-generator
  • export word document

Basic integration

Import jar package

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
复制代码

Template attribute configuration

# freemarker静态资源配置
spring:
  freemarker:
    tempalte-loader-path: classpath:/templates
    cache: true
    charset: UTF-8
    check-template-location: true
    content-type: text/html
    expose-request-attributes: true
    expose-session-attributes: true
    request-context-attribute: request
    suffix: .ftl
复制代码

-illustrate:

  • tempalte-loader-path: Specifies the path to the template file.
  • cache: whether the file is cached
  • charset: set the character encoding of the file
  • content-type: the type of the file
  • suffix: file suffix
  • check-template-location: check whether the template file exists
  • expose-request-attributes: Whether to enable the request attribute, the default is false
  • expose-session-attributes: Whether to enable the HttpSession attribute

business realization

@Controller
public class UserController
{
    @RequestMapping("/user")
    public String showUser(Model model) 
    {
        List<User> users = new ArrayList<>();
        for (int i = 0; i < 10; i++) 
        {
            User user = new User();
            user.setId((long) i);
            user.setUsername("剑圣无痕" + i);
            user.setAddress("广东省人民路" + i+"号");
            users.add(user);
        }
        model.addAttribute("users", users);
        return "user";
    }
}

复制代码

view file

<table border="1">
    <tr>
        <td>用户编号</td>
        <td>用户名称</td>
        <td>用户地址</td>
    </tr>
    <#list users as user>
        <tr>
            <td>${user.id}</td>
            <td>${user.username}</td>
            <td>${user.address}</td>
        </tr>
    </#list>
</table>
复制代码

Note: This article will not explain the basic loops, conditions and other grammars of freemark. For details, you can check the official website

operation result

picture.png

other features

Through the above steps, we have realized the view rendering function of Spring Boot integrated with Freemark, but in the actual project, it is necessary to implement functions such as template setting and export of word documents, so how to achieve it through Freemark?

load a specific template

 public void sendFreemarkTemplateMail(String templateName,Mail mail)
    {
        HashMap<String, Object> map = new HashMap<>();
        map.put("companyName", "广东剑圣无痕股份有限公司");
        map.put("address", "广东省建设路1008号");
        map.put("phone", "13123456789");
        Template template;
        try
        {
            template = configurer.getConfiguration().getTemplate(templateName);
            String context = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
            mail.setBody(context);
            sendHtmlMail(mail);
        }
        catch (Exception e)
        {
           logger.error("send freemark error",e);
        }
    }
复制代码

The above is the setting of the sending mail template, and the output content of the template file is loaded through freemark to send the mail

Summarize

This article explains the integration of Freemark with Spring Boot. If you have any questions, please give feedback in time.

Guess you like

Origin juejin.im/post/7166455005770153991