freemaker的简单实现


第一步:导入测试依赖jar包


 <dependencies>
  <dependency>
  <groupId>org.freemarker</groupId>
  <artifactId>freemarker</artifactId>
  <version>2.3.23</version>
  </dependency>
  <dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
  </dependency>
  </dependencies>


第二步:编写模板

文件名字为:hellomoto.ftl

<html>
<body>
  呵呵:${username}<br>
  ${author}<br>
 
  freemaker模板,需要占位符${author}获取数据<br>
向往着平淡,却不甘于平凡<br>
打雷时要记住微笑,那是上天再给你拍照<br>
北国风光,千里冰封,万里雪飘<br>
望长城内外,分外妖娆,<br>
江山如此多娇,让无数英雄竞折腰<br>


</body>
</html>



第三步:测试代码



public class TestMain {
/**

* freemaker类似于jsp,相当于占位符,可以替换页面中的内容
* 占位符类似于EL表达式
* @throws IOException 
* @throws TemplateException 
* */ 
@Test
public void test1() throws IOException, TemplateException{
//1.创建一个configuration对象
Configuration configuration = new Configuration(Configuration.getVersion());
//2.设置模板文件的路径
configuration.setDirectoryForTemplateLoading(new File("F:\\oxygenEclipsesrc\\testfreemarker\\src\\main\\resources"));
 
//3.设置字符集
configuration.setDefaultEncoding("UTF-8");
//4.加载具体模板
Template template = configuration.getTemplate("hellomoto.ftl");
//5.创建数据源,数据源指的是带有数据的对象
Map<String ,Object> data = new HashMap<>();
data.put("username", "沁园春。雪");
data.put("author", "毛泽东");
Random random = new Random();
int nextInt = random.nextInt(1000);
//6.创建输出流,用于写出文件
FileWriter fileWriter = new FileWriter(new File("F:\\freemakertest\\"+nextInt+".html"));
//7.执行操作
template.process(data, fileWriter);
//8.关闭资源
fileWriter.close();
}
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值