Freemaker页面静态化入门案例

1、创建maven工程并导入Freemarker的maven坐标

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

2、创建模板文件,Freemarker的模板文件后缀可以任意,一般建议为ftl。

<html> <head><meta charset="utf-8"> <title>Freemarker入门</title> </head> <body><#--我只是一个注释,我不会有任何输出 --> ${name}你好,${message} </body> </html>

3、生成文件
使用步骤:
第一步:创建一个 Configuration 对象,直接 new 一个对象。构造方法的参数就是 freemarker的版本
号。
第二步:设置模板文件所在的路径。
第三步:设置模板文件使用的字符集。一般就是 utf-8。
第四步:加载一个模板,创建一个模板对象。
第五步:创建一个模板使用的数据集,可以是 pojo 也可以是 map。一般是 Map。
第六步:创建一个 Writer 对象,一般创建 FileWriter 对象,指定生成的文件名。
第七步:调用模板对象的 process 方法输出文件。
第八步:关闭流。

public static void main(String[] args) throws Exception{ //1.创建配置类 Configuration configuration=new Configuration(Configuration.getVersion()); 
//2.设置模板所在的目录 configuration.setDirectoryForTemplateLoading(new File("D:\\ftl")); 
//3.设置字符集
configuration.setDefaultEncoding("utf-8"); 
//4.加载模板 Template template = configuration.getTemplate("test.ftl");
//5.创建数据模型 Map map=new HashMap();
map.put("name", "张三"); map.put("message", "欢迎来到传智播客!");
//6.创建Writer对象 
Writer out =new FileWriter(new File("d:\\test.html")); 
//7.输出 
template.process(map, out); 
//8.关闭Writer对象 
out.close(); 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值