FreeMarker入门级使用及静态化

1. FreeMarker 介绍

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

FreeMarker是免费的,基于Apache许可证2.0版本发布。其模板编写为FreeMarker Template Language(FTL),属于简单、专用的语言。需要准备数据在真实编程语言中来显示,比如数据库查询和业务运算, 之后模板显示已经准备好的数据。在模板中,主要用于如何展现数据, 而在模板之外注意于要展示什么数据 [1] 。

1、模板+数据模型=输出

freemarker并不关心数据的来源,只是根据模板的内容,将数据模型在模板中显示并输出文件(通常为html,也
可以生成其它格式的文本文件)

2. FreeMarker 快速入门

freemarker作为springmvc一种视图格式,默认情况下SpringMVC支持freemarker视图格式。

需要创建Spring Boot+Freemarker工程用于测试模板。

1.1 创建测试工程

创建一个freemarker 的测试工程专门用于freemarker的功能测试与模板的测试。

pom.xml如下


    
        org.springframework.boot
        spring-boot-starter-freemarker
    
    
        org.springframework.boot
        spring-boot-starter-web
    
    
        org.projectlombok
        lombok
    
    
        com.squareup.okhttp3
        okhttp
    
    
        org.springframework.boot
        spring-boot-starter-test
    
    
        org.apache.commons
        commons-io
    

1.2 配置文件

配置application.yml和 logback-spring.xml,从cms工程拷贝这两个文件,进行更改, logback-spring.xml无需更改,application.yml内容如下:

server:
  port: 8088 #服务端口

spring:
  application:
    name: test-freemarker #指定服务名
  freemarker:
    cache: false  #关闭模板缓存,方便测试
    settings:
      template_update_delay: 0 #检查模板更新延迟时间,设置为0表示立即检查,如果时间大于0会有缓存不方便进行模板测试

1.3 创建模型类

在freemarker的测试工程下创建模型类型用于测试

package com.xuecheng.test.freemarker.model;
@Data
@ToString
public class Student {
    private String name;//姓名
    private int age;//年龄
    private Date birthday;//生日
    private Float mondy;//钱包
    private List friends;//朋友列表
    private Student bestFriend;//最好的朋友
}

1.4 创建模板

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

在templates下创建模板文件test1.ftl,模板中的${name}最终会被freemarker替换成具体的数据。




    
    Hello World!


Hello ${name}!


1.5 创建controller

创建Controller类,向Map中添加name,最后返回模板文件。

package com.xuecheng.test.freemarker.controller;
@RequestMapping("/freemarker")
@Controller
public class FreemarkerController {
    @Autowired
    RestTemplate restTemplate;
    @RequestMapping("/test1")
    public String freemarker(Map map){
        map.put("name","黑马程序员");
        //返回模板文件名称
        return "test1";
    }
}

1.6 创建启动类

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

1.7 测试

请求:http://localhost:8088/freemarker/test1

屏幕显示: Hello 黑马程序员!

3. FreeMarker 基础

3.1 核心指令

3.1.1 数据模型

Freemarker静态化依赖数据模型和模板,下边定义数据模型:

下边方法形参map即为freemarker静态化所需要的数据模型,在map中填充数据:

@RequestMapping("/test1")
public String freemarker(Map map){
    //向数据模型放数据
    map.put("name","黑马程序员");
    Student stu1 = new Student();
    stu1.setName("小明");
    stu1.setAge(18);
    stu1.setMondy(1000.86f);
    stu1.setBirthday(new Date());
    Student stu2 = new Student();
    stu2.setName("小红");
    stu2.setMondy(200.1f);
    stu2.setAge(19);
    //        stu2.setBirthday(new Date());
    List friends = new ArrayList<>();
    friends.add(stu1);
    stu2.setFriends(friends);
    stu2.setBestFriend(stu1);
    List stus = new ArrayList<>();
    stus.add(stu1);
    stus.add(stu2);
    //向数据模型放数据
    map.put("stus",stus);
    //准备map数据
    HashMap stuMap = new HashMap<>();
    stuMap.put("stu1",stu1);
    stuMap.put("stu2",stu2);
    //向数据模型放数据
    map.put("stu1",stu1);
    //向数据模型放数据
    map.put("stuMap",stuMap);
    //返回模板文件名称
    return "test1";
}

3.1.2 List指令

本节定义freemarker模板,模板中使用freemarker的指令,关于freemarker的指令需要知道:

  1. 注释,即<#‐‐和‐‐>,介于其之间的内容会被freemarker忽略
  2. 插值(Interpolation):即${..}部分,freemarker会用真实的值代替${..}
  3. FTL指令:和HTML标记类似,名字前加#予以区分,Freemarker会解析标签中的表达式或逻辑。
  4. 文本,仅文本信息,这些不是freemarker的注释、插值、FTL指令的内容会被freemarker忽略解析,直接输出内容。

在test1.ftl模板中使用list指令遍历数据模型中的数据:


    <#list stus as stu>
        
序号 姓名 年龄 钱包
${stu_index + 1} ${stu.name} ${stu.age} ${stu.mondy}

输出:

Hello 黑马程序员! 序号 姓名 年龄 钱包 1 小明 18 1,000.86 2 小红 19 200.1

说明:
_index:得到循环的下标,使用方法是在stu后边加"_index",它的值是从0开始

3.1.3 遍历Map数据

  1. 数据模型

    使用map指令遍历数据模型中的stuMap。

  2. 模板

    输出stu1的学生信息:
    姓名:${stuMap['stu1'].name}
    年龄:${stuMap['stu1'].age}
    输出stu1的学生信息:
    姓名:${stuMap.stu1.name}
    年龄:${stuMap.stu1.age}
    遍历输出两个学生信息:
    <#list stuMap?keys as k>
    序号 姓名 年龄 钱包
    ${k_index + 1} ${stuMap[k].name} ${stuMap[k].age} ${stuMap[k].mondy}
  3. 输出

    输出stu1的学生信息:
    姓名:小明
    年龄:18
    输出stu1的学生信息:
    姓名:小明
    年龄:18
    遍历输出两个学生信息:
    序号 姓名 年龄 钱包        
    1 小红 19 200.1         
    2 小明 18 1,000.86
    

3.1.4 if指令

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

  1. 数据模型:

    使用list指令中测试数据模型。

  2. 模板:

    
        <#list stus as stu>
            
    姓名 年龄 钱包
    style="background:red;">${stu.name} ${stu.age} ${stu.mondy}
  3. 输出:

    通过测试发现 姓名为小明的背景色为红色。

3.2 其它指令

3.2.1 运算符

  1. 算数运算符 FreeMarker表达式中完全支持算术运算,FreeMarker支持的算术运算符包括:+,-,*, /, %
  2. 逻辑运算符 逻辑运算符有如下几个: 逻辑与:&& 逻辑或:|| 逻辑非:!逻辑运算符只能作用于布尔值,否则将产生错误
  3. 比较运算符 表达式中支持的比较运算符有如下几个:
    1. =或者==:判断两个值是否相等.
    2. !=:判断两个值是否不等.
    3. >或者gt:判断左边值是否大于右边值
    4. >=或者gte:判断左边值是否大于等于右边值
    5. <或者lt:判断左边值是否小于右边值
    6. <=或者lte:判断左边值是否小于等于右边值

注意: =和!=可以用于字符串,数值和日期来比较是否相等,但=和!=两边必须是相同类型的值,否则会产生错误,而且FreeMarker是精确比较,"x","x ","X"是不等的.其它的运行符可以作用于数字和日期,但不能作用于字符串,大部分的时候,使用gt等字母运算符代替>会有更好的效果,因为 FreeMarker会把>解释成FTL标签的结束字符,当然,也可以使用括号来避免这种情况,如:<#if (x>y)>

3.2.2 空值处理

  1. 判断某变量是否存在使用 “??” 用法为:variable??,如果该变量存在,返回true,否则返回false

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

    <#if stus??>
        <#list stus as stu>
            ......    
         
    
    
  2. 缺失变量默认值使用 “!” 使用!要以指定一个默认值,当变量为空时显示默认值。

    例: ${name!''}表示如果name为空显示空字符串。

    如果是嵌套对象则建议使用()括起来。

    例: ${(stu.bestFriend.name)!''}表示,如果stubestFriendname为空默认显示空字符串。

3.2.3 内建函数

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

  1. 得到某个集合的大小

    ${集合名?size}

  2. 日期格式化

    • 显示年月日: ${today?date}
    • 显示时分秒:${today?time}
    • 显示日期+时间:​${today?datetime}
    • 自定义格式化: ${today?string("yyyy年MM月")}
  3. 内建函数c

    map.put("point", 102920122);
    point是数字型,使用${point}会显示这个数字的值,并且每三位使用逗号分隔。
    如果不想显示为每三位分隔的数字,可以使用c函数将数字型转成字符串输出
    ${point?c}

  4. 将json字符串转成对象

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

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

3.2.4 完整的模板



    
        
        Hello World!
    
    
        Hello ${name}!
        
<#list stus as stu>
序号 姓名 年龄 钱包
${stu_index + 1} style="background:red;">${stu.name} ${stu.age} ${stu.mondy}


输出stu1的学生信息:
姓名:${stuMap['stu1'].name}
年龄:${stuMap['stu1'].age}
输出stu1的学生信息:
姓名:${stu1.name}
年龄:${stu1.age}
遍历输出两个学生信息:
<#list stuMap?keys as k>
序号 姓名 年龄 钱包
${k_index + 1} ${stuMap[k].name} ${stuMap[k].age} ${stuMap[k].mondy}

<#if stus??> <#list stus as stu>
姓名 年龄 出生日期 钱包 最好的朋友 朋友个数 朋友列表
${stu.name!''} ${stu.age} ${(stu.birthday?date)!''} ${stu.mondy} ${(stu.bestFriend.name)!''} ${(stu.friends?size)!0} <#if stu.friends??> <#list stu.friends as firend> ${firend.name!''}

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

3.3 静态化测试

3.3.1 使用模板文件静态化

在test下创建测试类,并且将main下的resource/templates拷贝到test下,本次测试使用之前我们在main下创建的模板文件。

//基于模板生成静态化文件
@Test
public void testGenerateHtml() throws IOException, TemplateException {
    //创建配置类
    Configuration configuration=new Configuration(Configuration.getVersion());
    //设置模板路径
    String classpath = this.getClass().getResource("/").getPath();
    configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/"));
    //设置字符集
    configuration.setDefaultEncoding("utf‐8");
    //加载模板
    Template template = configuration.getTemplate("test1.ftl");
    //数据模型
    Map map = new HashMap<>();
    map.put("name","黑马程序员");
    //静态化
    String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
    //静态化内容
    System.out.println(content);
    InputStream inputStream = IOUtils.toInputStream(content);
    //输出文件
    FileOutputStream fileOutputStream = new FileOutputStream(new File("d:/test1.html"));
    int copy = IOUtils.copy(inputStream, fileOutputStream);
}

3.3.2 使用模板字符串静态化

//基于模板字符串生成静态化文件
@Test
public void testGenerateHtmlByString() throws IOException, TemplateException {
    //创建配置类
    Configuration configuration=new Configuration(Configuration.getVersion());
    //模板内容,这里测试时使用简单的字符串作为模板
    String templateString="" +
        "\n" +
        "    \n" +
        "    \n" +
        "    名称:${name}\n" +
        "    \n" +
        "";

    //模板加载器
    StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
    stringTemplateLoader.putTemplate("template",templateString);
    configuration.setTemplateLoader(stringTemplateLoader);
    //得到模板
    Template template = configuration.getTemplate("template","utf‐8");
    //数据模型
    Map map = new HashMap<>();
    map.put("name","黑马程序员");
    //静态化
    String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
    //静态化内容
    System.out.println(content);
    InputStream inputStream = IOUtils.toInputStream(content);
    //输出文件
    FileOutputStream fileOutputStream = new FileOutputStream(new File("d:/test1.html"));
    IOUtils.copy(inputStream, fileOutputStream);
}

你可能感兴趣的:(FreeMarker入门级使用及静态化)