栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

[模板引擎] freemarker独立环境使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

[模板引擎] freemarker独立环境使用

目录

资料引入依赖定义模板使用附

1. 工程结构示例2. 执行结果示例3. 示例源码

资料

官网
中文版

引入依赖
  
      org.freemarker
        freemarker
        2.3.31
    
定义模板



    
    Title


${username}


使用

使用模板分别输出到文件和变量

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

import java.io.*;
import java.nio.Buffer;
import java.util.HashMap;

public class FreemarkerDemo {
    public static void main(String[] args) throws IOException, TemplateException {
        // http://freemarker.foofun.cn/pgui_quickstart_createconfiguration.html
        // 创建配置实例 !!不需要重复创建 Configuration 实例; 它的代价很高,尤其是会丢失缓存。Configuration 实例就是应用级别的单例。
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
        // 设置配置实例信息
        cfg.setDirectoryForTemplateLoading(new File(ClassLoader.getSystemResource("template").getPath()));
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        // 获取模板
        Template template = cfg.getTemplate("test.ftl");
        // 创建数据模型
        HashMap map = new HashMap<>();
        map.put("username","张三");
        Writer out = new FileWriter("e:\freemarker_test_out.html");
        // 渲染模板 输出到文件
        template.process(map,out);
        // 资源关闭
        out.flush();
        out.close();
        // 渲染模板 输出到变量
        StringWriter reslut = new StringWriter();
        template.process(map,reslut);
        System.out.println(reslut.toString());
    }
}

附 1. 工程结构示例

2. 执行结果示例

控制台输出

输出到文件

3. 示例源码

https://gitee.com/master336/template-engine-demo

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/721119.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号