博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Freemarker 模板引擎
阅读量:2056 次
发布时间:2019-04-28

本文共 16110 字,大约阅读时间需要 53 分钟。

Freemarker 模板引擎

1. FreeMarker介绍在这里插入图片描述

  1. freemarker是一个用Java开发的模板引擎

常用的java模板引擎还有哪些?

Jsp、Freemarker、Thymeleaf 、Velocity 等。

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

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

    1.数据模型

    数据模型在java中可以是基本类型也可以List、Map、Pojo等复杂类型。
    2.来自官方的例子:(https://freemarker.apache.org/docs/dgui_quickstart_basics.html)
    数据模型:
    在这里插入图片描述

    模板:

    在这里插入图片描述
    输出:
    在这里插入图片描述

1.2 FreeMarker快速入门

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

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

创建测试工程

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

pom.xml如下

xc-framework-parent
com.xuecheng
1.0-SNAPSHOT
../xc-framework-parent/pom.xml
4.0.0
test-freemarker
org.springframework.boot
spring-boot-starter-freemarker
org.projectlombok
lombok
com.squareup.okhttp3
okhttp
org.apache.commons
commons-io
org.springframework.boot
spring-boot-starter-test
org.springframework.boot
spring-boot-starter-web

配置文件

application.yml内容如下:

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

创建模型类

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

package com.xuecheng.test.freemarker.model;import lombok.Data;import lombok.ToString;import java.util.Date;import java.util.List;/** * @author 嘿嘿嘿1212 * @version 1.0 * @date 2019/11/16 21:04 */@Data@ToStringpublic class Student {
private String name;//姓名 private int age;//年龄 private Date birthday;//生日 private Float money;//钱包 private List
friends;//朋友列表 private Student bestFriend;//最好的朋友}

创建模板

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

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

    
Hello World!Hello ${name}!
<#if stus??> <#list stus as stu>
序号 姓名 年龄 钱包 出生日期
${stu_index + 1} <#if stu.name=="小明">style="background-color: beige"
>${stu.name}
<#if stu.money gt 300>style="background-color: red"
>${stu.age}
${stu.money} ${(stu.birthday?string("YYYY年MM月dd日"))!''}
遍历数据模型中的stuMap(map数据),第一种方法:在中括号中填写map的key,第二种方法:在map后边直接加"点key值"
输出stu1的学生信息:
<#if stuMap?? && stuMap.stu1??> 姓名:${stuMap['stu1'].name}
年龄:${stuMap['stu1'].age}
姓名:${stuMap.stu1.name}
年龄:${stuMap.stu1.age}
遍历map中的key,stuMap?keys就是key列表(是一个list),
<#list stuMap?keys as k>
学生的个数:${stus?size} ${point?c}
序号 姓名 年龄 钱包
${k_index+1} ${(stuMap[k].name)!''} ${(stuMap[k].age)!''} ${(stuMap[k].money)!''}
<#if stus??> <#list stus as stu>
姓名 年龄 出生日期 钱包 最好的朋友 朋友个数 朋友列表
${stu.name!''} ${stu.age} ${(stu.birthday?date)!''} ${stu.money} ${(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}

创建controller

package com.xuecheng.test.freemarker.controller;import com.xuecheng.test.freemarker.model.Student;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.ResponseEntity;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.client.RestTemplate;import java.util.*;/** * @author 嘿嘿嘿1212 * @version 1.0 * @date 2019/11/16 21:08 */@Controller//这里不要使用@RestController,要输出html页面,RestController输出的是json数据@RequestMapping("/freemarker")public class FreemarkerController {
@Autowired private RestTemplate restTemplate; @RequestMapping("/index_banner") public String indexBanner(Map
map) {
//使用restTemplate请求轮播图的模型数据 ResponseEntity
forEntity = restTemplate.getForEntity("http://localhost:31001/cms/config/getmodel/5a791725dd573c3574ee333f", Map.class); Map body = forEntity.getBody(); //设置模型数据 map.putAll(body); return "index_banner"; } @RequestMapping("/test1") public String test1(Map
map) {
map.put("name", "唐小智"); 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); // 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); map.put("point", 102920122); //返回freemarker模板的位置,基于resources/templates路径的 return "test1"; }}

创建启动类

package com.xuecheng.test.freemarker;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.Bean;import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;import org.springframework.web.client.RestTemplate;@SpringBootApplicationpublic class FreemarkerTestApplication {
public static void main(String[] args) {
SpringApplication.run(FreemarkerTestApplication.class, args); } @Bean public RestTemplate restTemplate(){
return new RestTemplate(new OkHttp3ClientHttpRequestFactory()); }}

测试

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

屏幕显示:Hello 唐小智!

1.3 FreeMarker基础

核心指令

数据模型

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

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

@RequestMapping("/test1")    public String test1(Map
map) {
map.put("name", "唐小智"); 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); // 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); map.put("point", 102920122); //返回freemarker模板的位置,基于resources/templates路径的 return "test1"; }

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}

遍历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}

if指令

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

则跳过内容不再输出。

  1. 数据模型

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

  2. 模板

    <#list stus as stu>
    姓名 年龄 钱包
    <#if stu.name =='小明'>style="background:red;"
    >${stu.name}
    ${stu.age} ${stu.mondy}

    通过阅读上边的代码,实现的功能是:如果姓名为“小明”则背景色显示为红色。

其它指令

运算符

  1. 算数运算符 FreeMarker表达式中完全支持算术运算,FreeMarker支持的算术运算符包括:+, - , * , / , %

  2. 逻辑运算符 逻辑运算符有如下几个: 逻辑与:&& 逻辑或:|| 逻辑非:! 逻辑运算符只能作用于布尔值,否则将产生错误

  3. 比较运算符 表达式中支持的比较运算符有如下几个:

  4. =或者==:判断两个值是否相等.

  5. !=:判断两个值是否不等.

  6. 或者gt:判断左边值是否大于右边值 4 >=或者gte:判断左边值是否大于等于右边值

  7. <或者lt:判断左边值是否小于右边值

  8. <=或者lte:判断左边值是否小于等于右边值

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

空值处理

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

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

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

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

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

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

内建函数

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

  1. 和到某个集合的大小

    ${集合名?size}

  2. 日期格式化

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

    map.put(“point”, 102920122);

    point是数字型,使用 p o i n t 会 显 示 这 个 数 字 的 值 , 不 并 每 三 位 使 用 逗 号 分 隔 。 如 果 不 想 显 示 为 每 三 位 分 隔 的 数 字 , 可 以 使 用 c 函 数 将 数 字 型 转 成 字 符 串 输 出 ‘ {point}会显示这个数字的值,不并每三位使用逗号分隔。 如果不想显示为每三位分隔的数字,可以使用c函数将数字型转成字符串输出 ` point使使c{point?c}`

  4. 将json字符串转成对象

    一个例子:

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

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

静态化测试

使用freemarker将页面生成html文件,测试html文件生成的方法:

  1. 使用模板文件静态化
    定义模板文件,使用freemarker静态化程序生成html文件。
  2. 使用模板字符串静态化
    定义模板字符串,使用freemarker静态化程序生成html文件。

使用模板文件静态化

  1. 创建模板文件(使用之前创建过测试文件)

        
    Hello World!Hello ${name}!
    <#if stus??> <#list stus as stu>
    序号 姓名 年龄 钱包 出生日期
    ${stu_index + 1} <#if stu.name=="小明">style="background-color: beige"
    >${stu.name}
    <#if stu.money gt 300>style="background-color: red"
    >${stu.age}
    ${stu.money} ${(stu.birthday?string("YYYY年MM月dd日"))!''}
    遍历数据模型中的stuMap(map数据),第一种方法:在中括号中填写map的key,第二种方法:在map后边直接加"点key值"
    输出stu1的学生信息:
    <#if stuMap?? && stuMap.stu1??> 姓名:${stuMap['stu1'].name}
    年龄:${stuMap['stu1'].age}
    姓名:${stuMap.stu1.name}
    年龄:${stuMap.stu1.age}
    遍历map中的key,stuMap?keys就是key列表(是一个list),
    <#list stuMap?keys as k>
    学生的个数:${stus?size} ${point?c}
    序号 姓名 年龄 钱包
    ${k_index+1} ${(stuMap[k].name)!''} ${(stuMap[k].age)!''} ${(stuMap[k].money)!''}
    <#if stus??> <#list stus as stu>
    姓名 年龄 出生日期 钱包 最好的朋友 朋友个数 朋友列表
    ${stu.name!''} ${stu.age} ${(stu.birthday?date)!''} ${stu.money} ${(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}
  2. 测试类(基于Spring Boot)

    @Test    public void testGenerateHtml() throws Exception {
    //定义配置类 Configuration configuration = new Configuration(Configuration.getVersion()); //定义模板路径 String classpath = this.getClass().getResource("/").getPath(); configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/")); //获取模板文件的内容 Template template = configuration.getTemplate("test1.ftl"); //定义数据模型 Map map = getMap(); //静态化 String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);// System.out.println(content); InputStream inputStream = IOUtils.toInputStream(content); FileOutputStream outputStream = new FileOutputStream(new File("E:\\可开采文件\\传智播放器(Windows)\\加密\\学成在线\\day04 页面静态化\\视频\\a.html")); //输出文件 IOUtils.copy(inputStream, outputStream); inputStream.close(); outputStream.close(); }

    测试结果得到指定文件,并且拥有静态化后的数据

使用模板字符串静态化

//基于模板文件的内容(字符串)生成html文件    @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"); //定义数据模型 HashMap
map = new HashMap<>(); map.put("name", "你是个魔鬼吗?"); //静态化 String context = FreeMarkerTemplateUtils.processTemplateIntoString(template, map); System.out.println(context); InputStream inputStream = IOUtils.toInputStream(context); //输出文件 FileOutputStream outputStream = new FileOutputStream(new File("E:\\可开采文件\\传智播放器(Windows)\\加密\\学成在线\\day04 页面静态化\\视频\\a.html")); IOUtils.copy(inputStream, outputStream); }

转载地址:http://onilf.baihongyu.com/

你可能感兴趣的文章
leetcode 130. Surrounded Regions
查看>>
【托业】【全真题库】TEST2-语法题
查看>>
博客文格式优化
查看>>
【托业】【新托业全真模拟】疑难语法题知识点总结(01~05)
查看>>
【SQL】group by 和order by 的区别。
查看>>
【F12】谷歌浏览器--前台效果可以在不访问服务器的前提下直接改样式看效果是否是预期值。...
查看>>
【Python】详解Python多线程Selenium跨浏览器测试
查看>>
Jmeter之参数化
查看>>
Shell 和Python的区别。
查看>>
Python 列表(list)、字典(dict)、字符串(string)常用基本操作小结
查看>>
Loadrunner之https协议录制回放报错如何解决?(九)
查看>>
python中xrange和range的异同
查看>>
列表、元组、集合、字典
查看>>
【Python】easygui小甲鱼
查看>>
【Python】关于Python多线程的一篇文章转载
查看>>
【Pyton】【小甲鱼】文件
查看>>
【Pyton】【小甲鱼】永久存储:腌制一缸美味的泡菜
查看>>
【Pyton】【小甲鱼】异常处理:你不可能总是对的
查看>>
APP性能测试工具
查看>>
【Pyton】【小甲鱼】类和对象
查看>>