FreeMarker基础配置

    xiaoxiao2025-12-03  2

    freemarker 版本

    官网下载地址 http://freemarker.org/freemarkerdownload.html

    当前测试所用版本为:freemarker-2.3.23

    文件结构

    1. 模板文件:test02.ftl

    <html> <head> <title>Welcome!</title> </head> <body> <h1>Welcome ${user}!</h1> <p>Our latest product: <a href="${latestProduct.url}">${latestProduct.name}</a>! </body> </html>

    2. Java 测试类文件:Test.java

    package com.freemarker.test02.base; import freemarker.template.*; import java.util.*; import java.io.*; public class Test { public static void main(String[] args) throws Exception { // 创建 Freemarker 配置实例 Configuration cfg = new Configuration(Configuration.VERSION_2_3_23); // 指定模板文件从何处加载的数据源,这里设置成一个文件目录。 cfg.setDirectoryForTemplateLoading(new File("templates")); cfg.setDefaultEncoding("UTF-8"); // 简单地重新抛出异常; 这应该在大多数生产系统中使用。 cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); // 创建一个数据模型 Map root = new HashMap(); root.put("user", "Big Joe"); Map latest = new HashMap(); root.put("latestProduct", latest); latest.put("url", "products/greenmouse.html"); latest.put("name", "green mouse"); // 获取模板(使用内部缓存) Template temp = cfg.getTemplate("test02.ftl"); // 合并数据模型模板 Writer out = new OutputStreamWriter(System.out); temp.process(root, out); out.flush(); out.close(); // 注意: ------------ // 为了简单起见,这里压制了异常(在方法签名中声明了异常,译者注),而在正式运行的产品中不要这样做。 } }

    运行结果

    <html> <head> <title>Welcome!</title> </head> <body> <h1>Welcome Big Joe!</h1> <p>Our latest product: <a href="products/greenmouse.html">green mouse</a>! </body> </html>
    转载请注明原文地址: https://ju.6miu.com/read-1304572.html
    最新回复(0)