Freemaker入门程序

1.创建普通的工程即可

2.添加依赖

<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.23</version>
</dependency>

3.创建freekamer.ftl模板

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<#--s-->
<h1>欢迎:${username}</h1>
<h1>年龄:${age}</h1>
</body>
</html>

4.编写测试程序生成静态页面

package com.fuke.myTest;
import com.sun.org.apache.bcel.internal.generic.NEW;
import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;

public class MyTest {
    public static void main(String[] args) {
        /*
        第一步:创建一个 Configuration 对象,直接 new 一个对象。构造方法的参数就是 freemarker的版本号。
        第二步:设置模板文件所在的路径。
        第三步:设置模板文件使用的字符集。一般就是 utf-8.
        第四步:加载一个模板,创建一个模板对象。
        第五步:创建一个模板使用的数据集,可以是 pojo 也可以是 map。一般是 Map。
        第六步:创建一个 Writer 对象,一般创建一 FileWriter 对象,指定生成的文件名。
        第七步:调用模板对象的 process 方法输出文件。
        第八步:关闭流
         */
        FileWriter fileWriter = null;
        Configuration configuration = new Configuration(Configuration.getVersion());
        try {
            configuration.setDirectoryForTemplateLoading(new File("E:\\idea项目空间\\FreeMarkerDemo\\src\\main\\resources\\ftl"));
            configuration.setDefaultEncoding("utf-8");
            Template template = configuration.getTemplate("MyFreeMarker.ftl");
            HashMap hashMap = new HashMap();
            hashMap.put("username","张三");
            hashMap.put("age",15);
            fileWriter = new FileWriter(new File("E:" + File.separator + "myFreeMaker.html"));
            template.process(hashMap,fileWriter);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(fileWriter!=null){
                try {
                    fileWriter.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

assign指令

assign指令可以定义变量,或者对象,可以在当前页面使用这些变量,并且在生成html会自动解析成对应的值

<#assign myName="dp" />
<#assign user={"name":"po","birthday":"2016"}/>
<span>${myName}</span> <br>
<span>${user.name}:${user.birthday}</span>

list指令

list可以对集合或数组进行遍历,例如存储的字符串strList 的遍历格式是 strList as str,利用${str_index}可以取出当前遍历的下标
遍历一般的字符串集合类型

<#list strList as str>
    ${str_index}------${str}
</#list>

遍历对象集合类型

<#list userList as user>
    ${user_index}------${user.name}
</#list>

if指令

<#list userList as user>
    <#if user.name="鲁班">
        <h3>${user.name}---判断正确</h3>
        <#else>
            <h3>${user.name}----判断失败</h3>
    </#if>
</#list>

include指令

include指令可以引入其他页面

<#include "test2.ftl">
发布了47 篇原创文章 · 获赞 6 · 访问量 2185

猜你喜欢

转载自blog.csdn.net/weixin_44467251/article/details/103397999
今日推荐