首先引入jar包
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
public class TestFreeMarker {
@Test
public void testFreemarker() throws Exception {
//1.創建一個模板文件
//2.創建一個Configuration對象
Configuration configuration = new Configuration(Configuration.getVersion());
//3.設置模板所在的路徑
configuration.setDirectoryForTemplateLoading(new File("E:/PROJECT/taotaot-item-web/src/main/webapp/WEB-INF/ftl"));
//4.設置模板的字符集,一般utf-8
configuration.setDefaultEncoding("utf-8");
//5.使用Configuration對象加載一個模板文件,需要指定模板文件的文件名。
Template template = configuration.getTemplate("hello.ftl");
// Template template = configuration.getTemplate("student.ftl");
//6.創建一個數據集,可以是pojo也可以是map,推薦使用map
Map data = new HashMap<>();
data.put("hello", "hello world");
//7.創建一個Writer對象,指定輸出文件的路徑及文件名。
Writer out = new FileWriter(new File("D:/temp/hello.text"));
//8.使用模板對象的process方法輸出文件。
template.process(data, out);
//9.關閉流
out.close();
}
}
E:/PROJECT/taotaot-item-web/src/main/webapp/WEB-INF/ftl這個文件夾下面創建一個hello.ftl文件 裏面的內容
${hello}就像一個el表達式取
data.put("hello", "hello world");