2017年1月19日 星期四

FreeMaker Hello World

官網連結


<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.25-incubating</version>
</dependency>
--------------------
public class Clazz {
    private Integer cid;
    private String cname;
    private Set<Student> setStudent = new HashSet<>();
    private Map<String, String> map = new HashMap<>();
    
    // setter/getter...
}
--------------------
public class Student {
    private Integer sid;
    private String sname;
    
    // setter/getter...
}

※new一個簡單的project就可以了,因為我想測試List,所以寫個一對多的java Bean



Configuration cfg = new Configuration(Configuration.VERSION_2_3_25);
cfg.setDirectoryForTemplateLoading(new File("src/main/java/resources"));
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
cfg.setLogTemplateExceptions(false);
    
// 單一
Map<String, Object> root = new HashMap<>();
root.put("xxx", "bruce");
root.put("ifElse", 2);
    
// 一對多
Clazz clazz = new Clazz();
clazz.setCid(1);
clazz.setCname("a");
    
Set<Student> set = new HashSet<>();
Student stu1 = new Student();
stu1.setSid(101);
stu1.setSname("aaa");
    
Student stu2 = new Student();
stu2.setSid(102);
stu2.setSname("bbb");
    
Student stu3 = new Student();
stu3.setSid(103);
stu3.setSname("ccc");
    
set.add(stu1);
set.add(stu2);
set.add(stu3);
    
clazz.setSetStudent(set);
    
// Map
Map<String, String> map = new HashMap<>();
map.put("I", "1");
map.put("II", "2");
map.put("III", "3");
clazz.setMap(map);
    
root.put("ooo", clazz);
Template temp = cfg.getTemplate("xxx.ftl");
Writer out = new OutputStreamWriter(System.out);
temp.process(root, out);

※Configuration一些有的沒的,可到官網複製

※這裡要注意setDirectoryForTemplateLoading("")和Template temp = cfg.getTemplate("xxx.ftl")
一個設定資料夾,一個設定檔案,ftl就是下面的HTML格式,不一定要要HTML格式,副檔名也不一定要叫ftl,只要裡面是純文本即可


<html>
    <head>
        <title>This is a Test!</title>
    </head>
    <body>
        xxx = ${xxx}
    
        <#if ifElse == 1>
            是1
        <#elseif ifElse == 2>
            是2
        <#else>
            不是1,也不是2
        </#if>
    
        cid = ${ooo.cid}
        Clazz = ${ooo}
        cname = ${ooo.cname}
    
        <#-- 我是註解 -->
        <#-- ${ooo.setStudent.sid} list不能這樣用-->
    
        <#list ooo.setStudent as item>
            ${item.sid}
        </#list>
    
        <#-- Map 2.3.25(含) 以上才能用 -->
        <#list ooo.map as k, v>
            ${k} - ${v}
        </#list>
    
    </body>
</html>

※if else 好像不能判斷字串,一執行都會錯,但我是直接點if else的超連結,沒有每一篇都看

※此次專案的圖如下:


沒有留言:

張貼留言