java工程中使用freemarker例子

來源:互聯網
上載者:User

標籤:建立   output   blog   運行   wrap   目錄   port   htm   建立   

建立java project,引入freemarker.jar, 本工程是用的版本:freemarker-2.3.20 版本

java工程目錄如下:

test.ftl檔案

HTML代碼

1 name : ${name}  2 age : ${age}  

Java代碼

 1 package com.freemarker; 2  3 import java.io.File; 4 import java.io.IOException; 5 import java.io.OutputStreamWriter; 6 import java.io.Writer; 7 import java.util.HashMap; 8 import java.util.Map; 9 10 import freemarker.template.Configuration;11 import freemarker.template.Template;12 import freemarker.template.TemplateException;13 14 public class Test {15     public static void main(String[] args) throws IOException, TemplateException {16 17         //1.建立配置執行個體Cofiguration18         Configuration cfg = new Configuration();19 20         //2.設定模板檔案目錄21         //(1)src目錄下的目錄(template在src下)22         //cfg.setDirectoryForTemplateLoading(new File("src/template"));23         //(2)完整路徑(template在src下)24         //cfg.setDirectoryForTemplateLoading(new File(25         //      "D:/cpic-env/workspace/javaFreemarker/src/template"));26         //cfg.setDirectoryForTemplateLoading(new File("src/template"));27         //(3)工程目錄下的目錄(template/main在工程下)--推薦28         cfg.setDirectoryForTemplateLoading(new File("template/main"));29         //cfg.setObjectWrapper(new DefaultObjectWrapper());30         //擷取模板(template)31         Template template = cfg.getTemplate("test.ftl");32         //建立資料模型(Map)33         Map<String, String> root = new HashMap<String, String>();34         root.put("name", "cxl");35         root.put("age", "25");36         //擷取輸出資料流(指定到控制台(標準輸出))37         Writer out = new OutputStreamWriter(System.out);38         //StringWriter out = new StringWriter();39         //System.out.println(out.toString());40         //資料與模板合并(資料+模板=輸出)41         template.process(root, out);42         out.flush();43     }44 }

運行結果:

java代碼

name : cxl  age : 25  

 

java工程中使用freemarker例子

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.