【模板引擎】微服务学习笔记六:freemarker模板引擎的常用命令介绍

本文涉及的产品
服务治理 MSE Sentinel/OpenSergo,Agent数量 不受限
简介: 【模板引擎】微服务学习笔记六:freemarker模板引擎的常用命令介绍

 一:🧸freemarker简介

       FreeMarker 是一款 模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页,电子邮件,配置文件,源代码等)的通用工具。 它不是面向最终用户的,而是一个Java类库,是一款程序员可以嵌入他们所开发产品的组件。

       模板编写为FreeMarker Template Language (FTL)。它是简单的,专用的语言,不是像PHP那样成熟的编程语言。 那就意味着要准备数据在真实编程语言中来显示,比如数据库查询和业务运算, 之后模板显示已经准备好的数据。在模板中,你可以专注于如何展现数据, 而在模板之外可以专注于要展示什么数据。

常用的java模板有jsp、Velocity、thmeleaf、freemarker等,它们之间的区别如下:

1.Jsp 为 Servlet 专用,不能单独进行使用。

2.Thymeleaf 为新技术,功能较为强大,但是执行的效率比较低。

3.Velocity从2010年更新完 2.0 版本后,便没有在更新。Spring Boot 官方在 1.4 版本后对此也不在支持,虽然 Velocity 在 2017 年版本得到迭代,但为时已晚。

4.Freemarker性能较好,是一款强大且轻量的模板语言。

二:🧸环境搭建

1.🧩创建工程&引入依赖

<dependencies>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!-- lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>
<!-- apache 对 java io 的封装工具库 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-io</artifactId>
    <version>1.3.2</version>
</dependency>
</dependencies>

image.gif

2.🧩添加配置文件

server:
  port: 8881 #服务端口
spring:
  application:
    name: freemarker-demo #指定服务名
  freemarker:
    cache: false  #关闭模板缓存,方便测试
    settings:
      template_update_delay: 0 #检查模板更新延迟时间,设置为0表示立即检查,如果时间大于0会有缓存不方便进行模板测试
    suffix: .ftl               #指定Freemarker模板文件的后缀名

image.gif

三:🧸模板测试

1.🧩创建一个实体类用于测试

package com.my.freemarker.entity;
import lombok.Data;
import java.util.Date;
@Data
public class Student {
    private String name;
    private int age;
    private Date birthday;
    private Float money;
}

image.gif

2.🧩创建模板

在resources下创建templates,此目录为freemarker的默认模板存放目录。

在templates下创建模板文件 01-basic.ftl ,模板中的插值表达式最终会被freemarker替换成具体的数据。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Hello World!</title>
</head>
<body>
<b>普通文本 String 展示:</b><br><br>
Hello ${name} <br>
<hr>
<b>对象Student中的数据展示:</b><br/>
姓名:${stu.name}<br/>
年龄:${stu.age}
<hr>
</body>
</html>

image.gif

3.🧩创建Controller

package com.my.freemarker.controller;
import com.my.freemarker.entity.Student;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class helloController {
    @GetMapping("/basic")
    public String helloTest(Model model){
        //1.纯文本形式参数
        model.addAttribute("name","freemarker");
        //2.实体类相关参数
        Student stu = new Student();
        stu.setName("小明");
        stu.setAge(19);
        stu.setMoney(100F);
        model.addAttribute("stu",stu);
        return "01-basic";
    }
}

image.gif

4.🧩创建启动类

package com.my.freemarker;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class FreemarkerApplication {
    public static void main(String[] args) {
        SpringApplication.run(FreemarkerApplication.class,args);
    }
}

image.gif

5.🧩进行测试

浏览器输入http:localhost:8881/basic

image.gif编辑

可以看到成功将数据展示出来。

四:🧸Freemarker常用语法

1:🧩基础语法种类

1.注释,即<#-- 内容 -->,介于其之间的内容会被freemarker当做注释处理

2.插值(interpolation):即${..}部分,freeremarker会用真实的值代替${..}

3.FTL指令:和HTML标记类似,名字前加#予以区分,Freeremarker会解析标签中的表达式或逻辑

<# > FTL指令 </#>

image.gif

4.文本,进文本信息,这些不是freeremarker的注释、插值、FTL指令的内容会被freeremarker忽略解析,直接输出其内容。

2:🧩集合指令(Map和List)

2.1:🎃创建对应的controller

@GetMapping("/list")
public String list(Model model){
    //------------------------------------
    Student stu1 = new Student();
    stu1.setName("小强");
    stu1.setAge(18);
    stu1.setMoney(1000.86f);
    stu1.setBirthday(new Date());
    //小红对象模型数据
    Student stu2 = new Student();
    stu2.setName("小红");
    stu2.setMoney(200.1f);
    stu2.setAge(19);
    //将两个对象模型数据存放到List集合中
    List<Student> stus = new ArrayList<>();
    stus.add(stu1);
    stus.add(stu2);
    //向model中存放List集合数据
    model.addAttribute("stus",stus);
    //------------------------------------
    //创建Map数据
    HashMap<String,Student> stuMap = new HashMap<>();
    stuMap.put("stu1",stu1);
    stuMap.put("stu2",stu2);
    // 3.1 向model中存放Map数据
    model.addAttribute("stuMap", stuMap);
    return "02-list";
}

image.gif

2.2:🎃模板实现

在templates包中添加"02-list.ftl"

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Hello World!</title>
</head>
<body>
<#-- list 数据的展示 -->
<b>展示list中的stu数据:</b>
<br>
<br>
<table>
    <tr>
        <td>序号</td>
        <td>姓名</td>
        <td>年龄</td>
        <td>钱包</td>
    </tr>
    <#list stus as stu>
        <tr>
            <td>${stu_index+1}</td>   <!-- index:得到循环的下标,使用方法是在stu后边加"_index",它的值是从0开始 -->
            <td>${stu.name}</td>
            <td>${stu.age}</td>
            <td>${stu.money}</td>
        </tr>
    </#list>
</table>
<hr>
<#-- Map 数据的展示 -->
<b>map数据的展示:</b>
<br/><br/>
<a href="###">方式一:通过map['keyname'].property</a><br/>
输出stu1的学生信息:<br/>
姓名:${stuMap['stu1'].name}<br/>
年龄:${stuMap['stu1'].age}<br/>
<br/>
<a href="###">方式二:通过map.keyname.property</a><br/>
输出stu2的学生信息:<br/>
姓名:${stuMap.stu2.name}<br/>
年龄:${stuMap.stu2.age}<br/>
<br/>
<a href="###">遍历map中两个学生信息:</a><br/>
<table>
    <tr>
        <td>序号</td>
        <td>姓名</td>
        <td>年龄</td>
        <td>钱包</td>
    </tr>
    <#list stuMap?keys as key >
        <tr>
            <td>${key_index}</td>
            <td>${stuMap[key].name}</td>
            <td>${stuMap[key].age}</td>
            <td>${stuMap[key].money}</td>
        </tr>
    </#list>
</table>
<hr>
</body>
</html>

image.gif

2.3:🎃测试

在浏览器地址栏输入http:localhost:8881/list

image.gif编辑

可以看到成功将数据展示

3.🧩if指令

       if 指令即判断指令,是常用的FTL指令,freemarker在解析时遇到if会进行判断,条件为真则输出if中间的内容,否则跳过内容不再输出。

<#if ></if>

image.gif

使用list指令中的数据作为数据模型,将名字为“小红”的数据输出为红色

<#list stus as stu>
    <#if stu.name = '小红'>
        <tr style="color: red">
            <td>${stu_index+1}</td>   <!-- index:得到循环的下标,使用方法是在stu后边加"_index",它的值是从0开始 -->
            <td>${stu.name}</td>
            <td>${stu.age}</td>
            <td>${stu.money}</td>
        </tr>
        <#else >
            <tr>
                <td>${stu_index+1}</td>
                <td>${stu.name}</td>
                <td>${stu.age}</td>
                <td>${stu.money}</td>
            </tr>
    </#if>
</#list>

image.gif

image.gif编辑

可以看到成功将“小红”变为红色。

4.🧩运算符

4.1:🎃算术运算符

FreeMarker表达式中支持+、-、*、/、%操作,只需要将运算表达式放入${}中即可。

4.2:🎃比较运算符

    • =或者==:判断两个值是否相等.
    • !=:判断两个值是否不等.
    • >或者gt:判断左边值是否大于右边值
    • >=或者gte:判断左边值是否大于等于右边值
    • <或者lt:判断左边值是否小于右边值
    • <=或者lte:判断左边值是否小于等于右边值

    4.3:🎃逻辑运算符

      • 逻辑与:&&
      • 逻辑或:||
      • 逻辑非:!

      逻辑运算符只能作用于布尔值,否则将产生错误 。

      5.🧩空值处理

      5.1:🎃判断某变量是否存在使用 “??”

      用法为:variable??,如果该变量存在,返回true,否则返回false

      例:为防止stus为空报错可以加上判断如下:

      <#if stus??>
      <#list stus as stu>
           ......
      </#list>
      </#if>

      image.gif

      5.2:🎃缺失变量默认值使用 “!”

        • 使用!要以指定一个默认值,当变量为空时显示默认值
          例: ${name!''}表示如果name为空显示空字符串。
        • 如果是嵌套对象则建议使用()括起来
          例: ${(stu.bestFriend.name)!''}表示,如果stu或bestFriend或name为空默认显示空字符串。

        6.🧩内建函数

        内建函数语法格式: 变量+?+函数名称

        6.1:🎃和到某个集合的大小

        ${集合名?size}

        6.2:🎃日期格式化

        显示年月日: ${today?date} 显示时分秒:${today?time} 显示日期+时间:${today?datetime} 自定义格式化: ${today?string("yyyy年MM月")}

        6.3:🎃内建函数c

        model.addAttribute("point", 102920122);

        point是数字型,使用${point}会显示这个数字的值,每三位使用逗号分隔。

        如果不想显示为每三位分隔的数字,可以使用c函数将数字型转成字符串输出

        ${point?c}

        6.4:🎃将json字符串转成对象

        一个例子:

        其中用到了 assign标签,assign的作用是定义一个变量。

        <#assign text="{'bank':'工商银行','account':'10101920201920212'}" />
        <#assign data=text?eval />
        开户行:${data.bank}  账号:${data.account}

        image.gif

        7.🧩静态化测试

               之前的测试都是SpringMVC将Freemarker作为视图解析器(ViewReporter)来集成到项目中,工作中,有的时候需要使用Freemarker原生Api来生成静态内容,下面一起来学习下原生Api生成文本文件(这里选择生成html文件)。

        7.1:🎃修改application.yml文件

        添加以下模板存放位置的配置信息,完整配置如下:

        server:
          port: 8881 #服务端口
        spring:
          application:
            name: freemarker-demo #指定服务名
          freemarker:
            cache: false  #关闭模板缓存,方便测试
            settings:
              template_update_delay: 0 #检查模板更新延迟时间,设置为0表示立即检查,如果时间大于0会有缓存不方便进行模板测试
            suffix: .ftl               #指定Freemarker模板文件的后缀名
            template-loader-path: classpath:/templates   #模板存放位置

        image.gif

        7.2:🎃在test下创建测试类

        package com.my.freemarker.test;
        import com.my.freemarker.FreemarkerApplication;
        import com.my.freemarker.entity.Student;
        import freemarker.template.Configuration;
        import freemarker.template.Template;
        import freemarker.template.TemplateException;
        import org.junit.jupiter.api.Test;
        import org.junit.runner.RunWith;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.boot.test.context.SpringBootTest;
        import org.springframework.test.context.junit4.SpringRunner;
        import java.io.FileWriter;
        import java.io.IOException;
        import java.util.*;
        @SpringBootTest(classes = FreemarkerApplication.class)
        @RunWith(SpringRunner.class)
        public class FreemarkerTest {
            @Autowired
            private Configuration configuration;
            @Test
            public void test() throws IOException, TemplateException {
                //freemarker模板对象,获取模板
                Template template = configuration.getTemplate("02-list.ftl");
                Map params = getData();
                template.process(params,new FileWriter("d:/headlinesPro/list.html"));
            }
            private Map getData() {
                Map<String,Object> map = new HashMap<>();
                //数据模型构建
                Student stu1 = new Student();
                stu1.setName("小强");
                stu1.setAge(19);
                stu1.setMoney(100F);
                stu1.setBirthday(new Date());
                Student stu2 = new Student();
                stu2.setName("小红");
                stu2.setAge(20);
                stu2.setMoney(1000F);
                stu2.setBirthday(new Date());
                //将两个对象放入List
                List<Student> list = new ArrayList<>();
                list.add(stu1);
                list.add(stu2);
                //向map中存放list数据
                map.put("stus",list);
                //创建mao数据
                HashMap<String,Student> stuMap = new HashMap<>();
                stuMap.put("stu1",stu1);
                stuMap.put("stu2",stu2);
                //向Map中存放Map数据
                map.put("stuMap",stuMap);
                return map;
            }
        }

        image.gif

        7.3:🎃结果展示

        image.gif编辑

        可以看到成功生成html文件,打开文件:

        image.gif编辑


        相关文章
        |
        4天前
        |
        SpringCloudAlibaba Java 网络架构
        【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(二)Rest微服务工程搭建
        【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(二)Rest微服务工程搭建
        66 0
        |
        4天前
        |
        SpringCloudAlibaba Java 网络架构
        【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(七)Spring Cloud Gateway服务网关
        【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(七)Spring Cloud Gateway服务网关
        125 0
        |
        4天前
        |
        SpringCloudAlibaba 负载均衡 Java
        【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(目录大纲)
        【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(目录大纲)
        74 1
        |
        4天前
        |
        Java Nacos Sentinel
        【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(九)Nacos+Sentinel+Seata
        【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(九)Nacos+Sentinel+Seata
        240 0
        |
        4天前
        |
        消息中间件 SpringCloudAlibaba Java
        【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(八)Config服务配置+bus消息总线+stream消息驱动+Sleuth链路追踪
        【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(八)Config服务配置+bus消息总线+stream消息驱动+Sleuth链路追踪
        796 0
        |
        4天前
        |
        SpringCloudAlibaba Java 测试技术
        【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(六)Hystrix(豪猪哥)的使用
        【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(六)Hystrix(豪猪哥)的使用
        50 1
        |
        4天前
        |
        SpringCloudAlibaba 负载均衡 Java
        【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(五)OpenFeign的使用
        【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(五)OpenFeign的使用
        51 0
        |
        4天前
        |
        负载均衡 算法 Java
        【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(四)Ribbon的使用
        【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(四)Ribbon的使用
        29 0
        |
        4天前
        |
        SpringCloudAlibaba 负载均衡 Java
        【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(三)Eureka服务注册中心
        【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(三)Eureka服务注册中心
        52 1
        |
        4天前
        |
        SpringCloudAlibaba Java 持续交付
        【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(一)基础知识+各个组件介绍+聚合父工程创建
        【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(一)基础知识+各个组件介绍+聚合父工程创建
        151 1