以maven为例
1.首先导入freemarker依赖包。
<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.20</version> </dependency>
2.建立source folder->src/main/resources,
在下面建立一个package-> ftl,
在ftl里面建立一个hello.ftl文件。
里面加入如下内容:
Hello:${username}
这个hello.ftl也就是freemarker用于生成文本的模板文件。
${username}里的username是要通过java代码往里面放的。
3.写一个测试类:
package com.lj.freemarker; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import org.junit.Test; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; public class TestFreemarker { @Test public void testHello() throws IOException, TemplateException{ //1.创建Configuration Configuration cfg=new Configuration(); //2.设计config中加载模板的路径 //设置了基于classpath加载路径,并且所有的模板文件都放在/ftl中。 cfg.setClassForTemplateLoading(TestFreemarker.class, "/ftl"); //3.获取模板文件,由于已经设置了默认的路径是/ftl,此时hello.ftl就是ftl包下面的文件 Template template=cfg.getTemplate("hello.ftl"); //4.创建数据文件,非常类似于OGNL,使用map来进行设置 Map<String,Object> root=new HashMap<String,Object>(); root.put("username", "alleni"); //5.通过模板和数据文件生成相应的输出 template.process(root, new PrintWriter(System.out)); } }
以上代码会在console输出:
Hello:alleni
如果我们想生成html文件,只要用eclipse生成一个html文件,再修改后缀为ftl,然后加入Hello:${username}这样的内容即可。
最后通过template.process(root, new PrintWriter(new File(目标文件))来生成。