FreeMarker入门细致教程

FreeMarker介绍:

FreeMarker 是一款模板引擎:基于 模板 + 数据 => 输出文本(html文件,json文件,java文件等)。在这里插入图片描述

入门案例:

  • 导入依赖:
<dependencies>
        <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>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
        </dependency>
    </dependencies>
  • 配置文件:
server:
  port: 8088
spring:
  application:
    name: test-ferrmarker
  freemarker:
    cache: false #关闭模板缓存,方便测试
    settings:
      template_update_delay: 0 #检查模板更新延迟时间,设置为0表示立即检查,如果时间大于0会有缓存不方便进行模板测试
  • Controller
@Controller
@RequestMapping("/freemarker")
public class FreemarkerController {
    @RequestMapping("/test1")
    public String test1(Map<String, Object> map) {
        map.put("name", "李志鹏");
        return "test1";
    }
}
  • template/test1.ftl
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
</head>
<body>
    Hello ${name}!
</body>
</html>
  • 访问页面展示效果:
    在这里插入图片描述

基础语法:

注释:<#-- 注释内容 -->
插值:${..},freemarker会用真事的数据代替${..}
FTL指令:和HTML标记类似,名字前加#予以区分,Freemarker会解析标签中的表达式或逻辑
文本:直接输出内容
  • List指令:
<#list stus as stu>
	 <tr>
	 	<td>${stu_index + 1}</td>
        <td>${stu.name}</td>
        <td>${stu.age}</td>
        <td>${stu.money}</td>
     </tr>
  </#list>
  • 遍历Map数据:
${stuMap['stu1'].name}
${stuMap['stu1'].age}
${stuMap.stu1.name}
${stuMap.stu1.age}
<#list stuMap?keys as k>
    姓名:${stuMap[k].name}<br/>
    年龄:${stuMap[k].age}<br/>
</#list>
  • if指令:
<#if stu.name=='李志鹏'>style="background: yellow"</#if>
<#if stu.money gt 9999>style="background: blue" </#if>
<#if (stu.money > 9999)>style="background: blue" </#if>
  • 空值处理:
??:判断某变量是否存在使用
<#if stus??>...</#if>
!: 缺失变量默认值使用!
${(stuMap['stu1'].name)!''}
${(stuMap.stu1.name)!''}
  • 内建函数:
显示集合大小:
${stus?size}
日期格式化:
显示年月日:${stu.birthday?date}
显示时分秒:${stu.birthday?time}
显示日期+时间:${stu.birthday?datetime}
自定义格式化:${stu.birthday?string("yyyy年MM日dd日")}
内建函数c:数字型转字符串输出:${point?c}
将json字符串转对象:
<#assign text="{'name':'李志鹏','age':'232'}"/>
<#assign data=text?eval />
姓名:${data.name} 年龄:${data.age}

Freemarker实现静态化

  • 基于ftl模本文件实现静态化
import com.xuecheng.test.freemarker.model.Student;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @author lzp
 * @version 1.0
 * @date 2020/3/16 13:50
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class FreemarkerTest {

    // 静态化测试,基于ftl模板文件生成html页面
    @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");
        // 加载ftl模板文件
        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("D:/idea_work/xczx/templates/test1.html"));
        // 输出文件
        IOUtils.copy(inputStream, outputStream);
        inputStream.close();
        outputStream.close();
    }

    // 获取数据模型
    public Map getMap() {
        Map<String, Object> map = new HashMap<>();
        map.put("name", "李志鹏");
        Student stu1 = new Student();
        stu1.setName("李志鹏");
        stu1.setAge(22);
        stu1.setMoney(10000f);
        stu1.setBirthday(new Date());
        Student stu2 = new Student();
        stu2.setName("黄园娥");
        stu2.setAge(21);
        stu2.setMoney(9999f);
        stu2.setBirthday(new Date());
        List<Student> friends = new ArrayList<>();
        friends.add(stu1);
        stu2.setFriends(friends);
        stu2.setBestFriend(stu1);
        ArrayList<Student> stus = new ArrayList<>();
        stus.add(stu1);
        stus.add(stu2);
        map.put("stus", stus);
        // 准备map数据
        Map<String, Student> stuMap = new HashMap<>();
        stuMap.put("stu1", stu1);
        stuMap.put("stu2", stu2);
        map.put("stu1", stu1);
        map.put("stuMap", stuMap);
        map.put("point", 1008611);
        return map;
    }
  • 基于模板字符串实现静态化
// 基于模板字符串生成html文件
    @Test
    public void testGenerateHtml2() throws IOException, TemplateException {
        // 创建配置类
        Configuration configuration = new Configuration(Configuration.getVersion());
        // 定义模板
        String templateString = "" +
                "<html>\n" +
                "<head></head>\n" +
                "<body>\n" +
                "   名称:${name}\n" +
                "</body>\n" +
                "</html>";
        // 使用模板加载器加载模板
        StringTemplateLoader templateLoader = new StringTemplateLoader();
        templateLoader.putTemplate("template", templateString);
        // 在配置中设置模板加载器
        configuration.setTemplateLoader(templateLoader);
        Template template = configuration.getTemplate("template", "utf-8");
        // 定义数据模型
        Map map = getMap();
        // 静态化
        String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
        // 静态化内容
        System.out.println(content);
        InputStream inputStream = IOUtils.toInputStream(content);
        FileOutputStream outputStream = new FileOutputStream(new File("D:/idea_work/xczx/templates/test2.html"));
        // 输出文件
        IOUtils.copy(inputStream, outputStream);
        inputStream.close();
        outputStream.close();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值