<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.23</version> </dependency>
模板文件中四種元素html
一、文本,直接輸出的部分
二、註釋,即<#--...-->格式不會輸出
三、插值(Interpolation):即${..}部分,將使用數據模型中的部分替代輸出
四、FTL指令:FreeMarker指令,和HTML標記相似,名字前加#予以區分,不會輸出。spa
咱們如今就建立一個簡單的建立模板文件test.ftlcode
<html>
<head>
<meta charset="utf-8">
<title>Freemarker入門小DEMO </title>
</head>
<body>
<#--我只是一個註釋,我不會有任何輸出 -->
${name},你好。${message}
張三 你好.
</body>
</html>
這裏有文本、插值和註釋htm
使用步驟:對象
第一步:建立一個 Configuration 對象,直接 new 一個對象。構造方法的參數就是 freemarker的版本號。blog
第二步:設置模板文件所在的路徑。utf-8
第三步:設置模板文件使用的字符集。通常就是 utf-8.get
第四步:加載一個模板,建立一個模板對象。it
第五步:建立一個模板使用的數據集,能夠是 pojo 也能夠是 map。通常是 Map。io
第六步:建立一個 Writer 對象,通常建立一 FileWriter 對象,指定生成的文件名。
第七步:調用模板對象的 process 方法輸出文件。
第八步:關閉流
代碼:
建立Test類 main方法以下:
//1.建立配置類
Configuration configuration=new Configuration(Configuration.getVersion()); //2.設置模板所在的目錄 configuration.setDirectoryForTemplateLoading(new File("D:/pinyougou_work/freemarkerDemo/src/main/resources/")); //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")); Idea Writer out =new PrintWriter(new File("d:\\test.html"),」UTF-8」); //7.輸出 template.process(map, out); //8.關閉Writer對象 out.close();
執行後,在D盤根目錄便可看到生成的test.html ,打開看看