1. 程式人生 > >freemarker入門小例子

freemarker入門小例子

我用freemarker做了兩個小例子,主要的東西是:兩個Test檔案,一個Animal實體類,一個ftl模板---freemarker的模板,我使用maven做的java工程案例。主要結構內容如下圖:

注意:需要匯入freemarker的jar包:

1.首先我們先來了解一下freemarker的概念:

FreeMarker是一個模板引擎,一個基於模板生成文字輸出的通用工具,使用純Java編寫;

FreeMarker被設計用來生成HTML Web頁面,特別是基於MVC模式的應用程式,雖然FreeMarker具有一些程式設計的能力,但通常由Java程式準備要顯示的資料,由FreeMarker生成頁面,通過模板顯示準備的資料。

FreeMarker不是一個Web應用框架,而適合作為Web應用框架一個元件
FreeMarker與容器無關,因為它並不知道HTTP或Servlet;
FreeMarker同樣可以應用於非Web應用程式環境
FreeMarker更適合作為Model2框架(如Struts)的檢視元件,你也可以在模板中使用JSP標記庫
FreeMarker是免費的

2.開始做簡單的例子,首先寫一個所需的實體類

public class Animal {

    private String name;
    private int price;

}

3.寫一個所需的freemarker模板,以備用(這是個用到內容較多的模板)

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome!</title>
</head>
<body>
<#--註釋部分-->
<#--下面使用插值-->
<h1>Welcome ${user}!</h1>
<p>We have these animals:</p>
<ul>
<#--使用FTL指令-->
<#list animals?sort_by("price")?reverse as being>
   <li>${being_index} ${being.name} for ${being.price} Euros</li>
</#list>
</ul>

<#if (score==10)>
    abcdefg
</#if><br/>
  
${(team?split(","))[1]}<br/>

<#list sexMap?keys as k>
   ${k}---${sexMap[k]}<br/>
</#list>
</body>
</html>

4.下面是一個最簡單的測試小例子

package demo;

import java.io.FileWriter;
import java.io.StringReader;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import freemarker.template.Template;

/***
 *  功能:freemarker最簡單例子
 *  
 *  時間: 2016-8-15 下午4:13:07
 */
public class Test1 {

    public static void main(String[] args) {
        try {
            // 建立插值的map
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("user", "rr");
            map.put("url", "http://www.baidu.com/");
            map.put("name", "百度");

            // 建立一個模板物件
            Template t = new Template(null, new StringReader(
                    "使用者名稱:${user};URL:    ${url};姓名:  ${name}"), null);

            // 執行插值,並輸出到指定的輸出流中
            Writer writer = new FileWriter("F:\\aa.html");
            t.process(map, writer);
            // t.process(map, new OutputStreamWriter(System.out));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

5.上面例子不用模板就可以執行,會在你寫的路徑裡生成你要的HTML檔案,開啟它,執行結果如下圖:(未解決亂碼問題)

6.這個例子用到了ftl模板,解決了亂碼問題。

package demo;

import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.bawei.entity.Animal;

import freemarker.template.Configuration;
import freemarker.template.Template;

/***
 * 
 * 時間: 2016-8-16 上午7:36:56
 */
public class Test2 {

    public static void main(String[] args) {
        Animal a1 = new Animal();
        a1.setName("小狗");
        a1.setPrice(88);
        Animal a2 = new Animal();
        a2.setName("小喵");
        a2.setPrice(80);

        List<Animal> list = new ArrayList<Animal>();
        list.add(a1);
        list.add(a2);
        
        Map<String,Object> sexMap=new HashMap<String,Object>();
        sexMap.put("1", "男");
        sexMap.put("0","女");

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("user", "冉冉");
        map.put("score", 13);
        map.put("team", "一班,二班");
        map.put("animals", list);
        map.put("sexMap",sexMap);
        try {
            Configuration config = new Configuration();
            
            config.setDefaultEncoding("UTF-8");
            config.setDirectoryForTemplateLoading(new File("F:\\xiangmu\\freemarker_Demo\\src\\test\\java\\demo"));
            
            Template template = config.getTemplate("hello.ftl");
            template.process(map,new FileWriter("F:\\bb.html"));
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
}

7.執行結果如下圖:

這樣做完小例子後就對freemarker有了簡單的瞭解,明天我們在深入瞭解freemarker,看它與如何spring整合的專案。

繼續努力

來源於: