FreeMarker 基本配置(一)
2015-07-11 17:03
260 查看
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>
相关文章推荐
- 【NOI 2010】能量采集&&超级钢琴
- Cocos2d-x制作跳棋第三步:棋子动作实现及AI算法思想
- 省队集训 water
- Notepad++
- 写写 icon font
- Android笔记-1
- Yii1.1 Active Record 查询结果转化成数组
- 1038. Recover the Smallest Number (30)
- Linux文件系统和目录结构
- 线程池 学习心得
- Java系列学习(十三)-字符串
- 关于欧姆龙PLC-CP1系列输入输出故障分析总结
- ADB的用法
- iOS系统网络抓包方法
- PCI Express基本原理和结构
- oracle监听服务无法启动解决办法
- 搜索函数 数独
- php扩展库
- [转载]Android开发必备的21个免费资源和工具
- [LeetCode] Populating Next Right Pointers in Each Node