freemarker在web應用項目的使用


FreeMarker是一個用Java語言編寫的模板引擎,它基於模板來生成文本輸出。FreeMarker與Web容器無關,即在Web運行時,它並不知道Servlet或HTTP。它不僅可以用作表現層的實現技術,而且還可以用於生成XML,JSP或Java 等。目前企業中:主要用Freemarker做靜態頁面或是頁面展示。

以下都是網上摘要,感覺很有用,適合初學者了解

Freemarker的使用方法

把freemarker的jar包添加到工程中

<dependency>
  <groupId>org.freemarker</groupId>
  <artifactId>freemarker</artifactId>
  <version>2.3.23</version>
</dependency>

首先需要添加freemarker.jar到項目,如果項目中有spring或者spirngmvc,需要整合,首先配置freemarkerConfig,代碼結構如下:

 

<!-- 設置freeMarker的配置文件路徑 -->
    <bean id="freemarkerConfiguration"
        class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="location" value="classpath:freemarker.properties" />
    </bean>
 
 
        <bean id="freemarkerConfig"
        class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="freemarkerSettings" ref="freemarkerConfiguration" /> 
<property name="templateLoaderPath"> <value>/WEB-INF/freemarker/</value> </property> <property name="freemarkerVariables"><!--設置一些常用的全局變量--> <map> <entry key="xml_escape" value-ref="fmXmlEscape" /> <entry key="webRoot" value="/shop"></entry> <entry key="jsRoot" value="/shop/js"></entry> </map> </property> </bean>

其中一下代碼是用來掃描.ftl的模板文件,在/web-info/freemarker目錄中

<property name="templateLoaderPath">
    <value>/WEB-INF/freemarker/</value>
</property>

然后freemarker用ftl文件來呈現視圖,這時候就需要配置freemarker的視圖解析器,代碼如下:

<!-- 配置freeMarker視圖解析器 -->
    <bean id="freemarkerViewResolver"
        class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView" 
            />
        <property name="viewNames" value="*.ftl" />
        <property name="contentType" value="text/html; charset=utf-8" />
        <property name="cache" value="true" />
        <property name="suffix" value="" />
    <!--     <property name="exposeRequestAttributes" value="true" />
        <property name="exposeSessionAttributes" value="true" />
        <property name="exposeSpringMacroHelpers" value="true" /> -->
        <property name="order" value="0" />
    </bean>
    <!-- 對模型視圖名稱的解析,即在模型視圖名稱添加前后綴 通用解析器 -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="" />
        <property name="viewNames" value="*.html,*.jsp" />
        <property name="suffix" value="" />
        <property name="viewClass"
            value="org.springframework.web.servlet.view.InternalResourceView" />
        <property name="order" value="1"></property>
    </bean>

其中:<property name="order" value="0">代表了第一個匹配的是freemarker的視圖解析器,如果匹配不成功,則自動選擇order=1的其他解析器,目前的通用解析器可以解析.html跟.jsp的視圖,如果需要其他視圖的解析器,可以自行添加。

其中的exposeRequestAttributes  exposeSessionAttributes兩個屬性都被設置為true。結果是請求和會話屬性都被復制到模板的屬性集中,可以使用FreeMarker的表達式語言來訪問並顯示。

 

使用這些宏,必須設置FreeMarkerViewResolver的exposeSpringMacroHelpers屬性為true

以上是freemarker與springmvc整合需要配置的xml文件。

下面來介紹一下在Java 代碼中如何使用:

    首先編寫Freemarker的工具類,用來生成HTML文件的方法:

package com.hc.shop.common.tools;
 
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
 
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;
 
import freemarker.template.Template;
import freemarker.template.TemplateException;
 
/**
 * @author HuifengWang 靜態化方法
 **/
public class FreeMarkerUtil {
    /**
     * 
     * 生成HTML靜態頁面的公公方法
     * @param fmc 
     * @param templateName 模板的名稱
     * @param request
     * @param map 生成模板需要的數據
     * @param filePath 相對於web容器的路徑
     * @param fileName 要生成的文件的名稱,帶擴展名
     * @author HuifengWang
     * 
     */
    public static void createHtml(FreeMarkerConfig fmc, String templateName,
            HttpServletRequest request, Map<?, ?> map, String filePath,
            String fileName) {
        Writer out = null;
        try {
            Template template = fmc.getConfiguration()
                    .getTemplate(templateName);
            String htmlPath = request.getSession().getServletContext()
                    .getRealPath(filePath)
                    + "/" + fileName;
            File htmlFile = new File(htmlPath);
            if (!htmlFile.getParentFile().exists()) {
                htmlFile.getParentFile().mkdirs();
            }
            if (!htmlFile.exists()) {
                htmlFile.createNewFile();
            }
            out = new OutputStreamWriter(new FileOutputStream(htmlPath),"UTF-8");
            template.process(map, out);
            out.flush();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
                out = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    
    /**
     * @param request
     * @param filePath  文件存放的路徑
     * @param fileName 文件的名稱,需要擴展名
     * @author HuifengWang
     * @return
     */
    public static Map<String,Object> htmlFileHasExist(HttpServletRequest request,String filePath,
            String fileName) {
        Map<String,Object> map = new HashMap<String,Object>();
        String htmlPath = request.getSession().getServletContext()
                .getRealPath(filePath)
                + "/" + fileName;
        File htmlFile = new File(htmlPath);
        if(htmlFile.exists()){
            map.put("exist", true);
        }else{
            map.put("exist",false);
        }
        return map ;
    }
}

以上就是要生成HTML文件的工具類,參數注解都有,應該很好理解。

 

如何在Controller中調用??下面來看一個很簡單的demo

 

@Autowired
    private FreeMarkerConfig freeMarkerConfig;//獲取FreemarkerConfig的實例
    
    @RequestMapping("/ttt")
    public String ttt(HttpServletRequest request,HttpServletResponse response,ModelMap mv) throws IOException, TemplateException, ServletException{
        String fileName ="ttt.html";
        Boolean flag =(Boolean)FreeMarkerUtil.htmlFileHasExist(request, FREEMARKER_PATH, fileName).get("exist");
        if(!flag){//如何靜態文件不存在,重新生成
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("user", "xiaowang小王");//這里包含業務邏輯請求等
            mv.addAllAttributes(map);
            FreeMarkerUtil.createHtml(freeMarkerConfig, "demo.ftl", request, map, FREEMARKER_PATH, fileName);//根據模板生成靜態頁面
        }
        return FREEMARKER_PATH+"/"+fileName;//始終返回生成的HTML頁面
    }

以上就是如何在springmvc中使用Freemarker的具體實現方式

 

那在springboot項目中如何整合呢

搭建springboot的web項目可以用idea搭建

在項目中的pom.xml中添加freemarker依賴,依賴如下

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

2.2在application.properties配置文件中對freemarker進行配置,配置如下;

server.port=8080
spring.freemarker.allow-request-override=false
spring.freemarker.cache=true
spring.freemarker.check-template-location=true
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.suffix=.html
spring.freemarker.templateEncoding=UTF-8
spring.freemarker.templateLoaderPath=classpath:/templates/
spring.freemarker.expose-spring-macro-helpers=false

 1) 控制層代碼

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**  
 * ClassName:StudentController 
 * Date:     2017年11月6日 下午4:27:40
 * @author   Joe  
 * @version    
 * @since    JDK 1.8
 */
@Controller
public class StudentController {
/**
     * freemarker:(跳轉到 freemarker.ftl).  
     * @author Joe
     * Date:2017年11月6日下午4:52:19
     *
     * @param map
     * @return
     */
    @RequestMapping("/freemarker")
    public String freemarker(Map<String, Object> map){
        map.put("name", "Joe");
        map.put("sex", 1);    //sex:性別,1:男;0:女;  
        
        // 模擬數據
        List<Map<String, Object>> friends = new ArrayList<Map<String, Object>>();
        Map<String, Object> friend = new HashMap<String, Object>();
        friend.put("name", "xbq");
        friend.put("age", 22);
        friends.add(friend);
        friend = new HashMap<String, Object>();
        friend.put("name", "July");
        friend.put("age", 18);
        friends.add(friend);
        map.put("friends", friends);
        return "freemarker";
    }
}

 2)在main\resources\templates 目錄下 新建 freemarker.ftl 文件,也可以是html的后綴,內容如下:

<!DOCTYPE html>  
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"  
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">  
    <head>  
        <title>Hello World!</title>  
    </head>  
    <body>
       <center>
       <p>  
           welcome ${name} to freemarker!  
       </p>        
        
       <p>性別:  
           <#if sex==0><#elseif sex==1><#else>  
                  保密     
           </#if>  
        </p>
        
       <h4>我的好友:</h4>  
       <#list friends as item>  
               姓名:${item.name} , 年齡${item.age}  
           <br>  
       </#list>  
       </center>
    </body>  
</html>

通過freemarker生成word文件

<!--添加freeMarker-->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.20</version>
        </dependency>

下一步我們要做的是先好我們的word模板然后將模板轉換為xml文件。在word模板中需要定義好我們的占位符哦,使用${string}的方式。“string”根據自己的愛好定義就好了。

過程如下:

word文檔:

 

 

 然后將我們的word文檔另存為xml文檔。

 

 

 將我們的xml文檔的后綴改為ftl,然后用可以打開ftl文件的軟件打開我們的ftl文件。在這里我們有幾個需要注意的地方。

第一,定義的占位符可能會被分開了。就像下面這樣:

 

 

 

我們需要做的就是刪掉多余的部分,圖中我定義的是${userName}.所以我就把多余的刪掉,變成${userName}就可以了。

第二,我們需要注意的就是在我們的表格部分需要自己添加freeMarker標簽。在表格代碼間用自定的標簽括起來。定義的參數要和我們在方法中定義的一致,否則無法取到值。

表格開始:

 

 

 

 結束:</list>

 

package czc.sup.system.model.six;



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

import java.io.*;
import java.util.Map;

public class WordUtil {

    /**
     * 生成word文件
     * @param dataMap word中需要展示的動態數據,用map集合來保存
     * @param templateName word模板名稱,例如:test.ftl
     * @param filePath 文件生成的目標路徑,例如:D:/wordFile/
     * @param fileName 生成的文件名稱,例如:test.doc
     */
    @SuppressWarnings("unchecked")
    public static void createWord(Map dataMap,String templateName,String filePath,String fileName){
        try {
            //創建配置實例
            Configuration configuration = new Configuration();

            //設置編碼
            configuration.setDefaultEncoding("UTF-8");

            //ftl模板文件
            configuration.setClassForTemplateLoading(WordUtil.class,"/");

            //獲取模板
            Template template = configuration.getTemplate(templateName);

            //輸出文件
            File outFile = new File(filePath+File.separator+fileName);

            //如果輸出目標文件夾不存在,則創建
            if (!outFile.getParentFile().exists()){
                outFile.getParentFile().mkdirs();
            }

            //將模板和數據模型合並生成文件
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));


            //生成文件
            template.process(dataMap, out);

            //關閉流
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
public static void main(String[] args) {
         /** 用於組裝word頁面需要的數據 */
        Map<String, Object> dataMap = new HashMap<String, Object>();
        DataWord dataWord = new DataWord("model", "name", "designCode", "code", "met", "date", "temp", "humi", "hly");
        List<Object> datas = new ArrayList<>();
        for(int i=0;i<10;i++){
            Data data = new Data("1","檢測名"+i, "norm", "result", "remark");
            datas.add(data);
        }
        dataMap.put("product",dataWord);
        dataMap.put("datas",datas);
        String filePath = "";
        if (IsWhatSystem.whatSystem()) {
            //文件路徑
            filePath = "D:/doc_f/";
        }else {
            filePath = "/doc_f/";
        }
        //文件唯一名稱
        String fileOnlyName = "生成Word文檔.doc";
        /** 生成word  數據包裝,模板名,文件生成路徑,生成的文件名*/
        WordUtil.createWord(dataMap, "quality.ftl", filePath, fileOnlyName);
    }

然后就在相應的目錄下導出word文檔了

通過freemarker生成excel文件

第一步:添加依賴

<dependency>  
   <groupId>org.freemarker</groupId>  
   <artifactId>freemarker</artifactId>  
   <version>2.3.20</version>  
</dependency>

第二步:把excel另存為xml

在這里我要說一下,excel在另存為xml時里面的圖片會丟失,它並不會像word那樣生成一個占位符。所以我這個導出的excel是沒有圖片的。言歸正傳,這就是我另存為的xml的樣例,其中row為行,cell為單元格

 

 

 

第三步:把要插入的數據使用freemarker的標簽----${}替換

看到這里的${},是不是覺得它很像jstl標簽,它的用法確實和jstl差不多,jstl是獲取session中的值,而他是獲取dataMap中的值;而且都是可以循環的便利的,它的便利標簽就是

<#list list as item><#--其中list為你后台在dataMap中的key-->
    <#if item.detaildata??><#--判斷是否為空,如果不為空則顯示內容-->

<#--${item.detaildata}是獲取list的子元素的值-->
 <Cell ss:StyleID="s37"><Data ss:Type="String">${item.detaildata}</Data></Cell>
   <#else><#--否則顯示空的單元格-->
   <Cell ss:StyleID="s37"/>
  </#if>
  </#list>

如圖

 

 

 第四步:把xml的后綴名改成ftl,並且在webapp中新建template,把xxx.ftl,放到里面

 

 

好了基本的操作已經做完了,下面就是后台代碼了。因為我的項目是MVC的設計理念並沒有使用任何框架,所以把后台分為了四個層面:數據庫對象序列化(dto),數據庫訪問層(DAO),數據處理層(service),控制層(servlet),算了還是用一個簡單的例子吧,我開發的項目可能就要從頭講了。廢話不多說先上service的代碼,是一個封裝好的類,可以直接調用的:

public class ExportExcelService {
    public static void export(String templatePath, Map<String, Object> dataMap,
            String buildFile, String newName,HttpServletRequest request,HttpServletResponse response) {
        try {
            ServletContext application = request.getSession().getServletContext();
            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("utf-8");
            String path = application.getRealPath("template");

// 此處是本類Class.getResource()相對於模版文件的相對路徑
            configuration.setDirectoryForTemplateLoading(new File(path));
            Template template = null;
            File outFile = new File(buildFile);
            Writer writer = null;
            template = configuration.getTemplate(templatePath);
            template.setEncoding("utf-8");
            writer = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(outFile), Charset.forName("utf-8")));// 此處為輸
            template.process(dataMap, writer);
            writer.flush();
            writer.close();
            // return true;
            // 設置response的編碼方式
            response.setContentType("application/x-msdownload");
            // 設置附加文件名
            response.setHeader("Content-Disposition", "attachment;filename="
                    + new String(newName.getBytes("utf-8"), "iso-8859-1"));
            // 讀出文件到i/o流
            FileInputStream fis = new FileInputStream(outFile);
            BufferedInputStream buf = new BufferedInputStream(fis);
            byte[] b = new byte[1024];// 相當於我們的緩存
            long k = 0;// 該值用於計算當前實際下載了多少字節
            // 從response對象中得到輸出流,准備下載
            OutputStream myout = response.getOutputStream();
            // 開始循環下載
            while (k < outFile.length()) {
                int j = buf.read(b, 0, 1024);
                k += j;
                // 將b中的數據寫到客戶端的內存
                myout.write(b, 0, j);
            }
            // 將寫入到客戶端的內存的數據,刷新到磁盤
            myout.flush();
            myout.close();
        } catch (Exception e) {
            e.printStackTrace();
            // return false;
        }
    }
}

然后我們在servlet中調用這個類中的方法,重點就看我標黃的代碼,這個是自己生成的list,而不是通過其他代碼生成的,標藍色的則是單一的鍵值對,紅色代碼為如果導出的數據不是模板的7天數據,則自動補充不足的空數據,以完成模板顯示空單元格如下:

@WebServlet("/excelExport")
public class exportExcelServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uz=new String(URLDecoder.decode(req.getParameter("uz"),"utf-8"));
        ReimburseService res=new ReimburseService();
        String[] data=uz.split(",");
        String uname=uz.split(",")[1];
        String weeknumber=uz.split(",")[0];
        Model model=res.querydetail(uname, weeknumber);
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("username",uz.split(",")[2]);
        dataMap.put("writedata",uz.split(",")[3]);
        dataMap.put("appartment",uz.split(",")[4]);
        List list=(List) model.getData();
        for(int i=list.size();i<7;i++){
            ReimburseDetail rd=new ReimburseDetail();
            rd.setDetaildata("");
            rd.setHotelfare("");
            rd.setLocation("");
            rd.setLongfare("");
            rd.setOtherfare("");
            rd.setShortfare("");
            rd.setProject("");
            rd.setFaredescription("");
             list.add(rd);
        }
        //對list進行排序
        for(int i=0;i<list.size();i++){
            ReimburseDetail rdl=(ReimburseDetail)list.get(i);
            try {
                if(!rdl.getDetaildata().equals("")){
                    int b=dayForWeek(rdl.getDetaildata());
                    if(b-1!=i){
                        Object objA= list.get(i);
                        list.set(i, list.get(b-1));
                        list.set(b-1, objA);
                    }
                }            
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        dataMap.put("list",list);
        List ls=new  ArrayList();
        String[] num={"A","B","C","D","E","F","G"};
        String[] Formula={"-9","-10","-11","-12","-13","-14","-15"};
        for(int i=0;i<num.length;i++){
            Map<String,Object> map = new HashMap<String,Object>();  
            map.put("num",num[i]);
            ReimburseDetail r=(ReimburseDetail)list.get(i);
            map.put("faredescription",r.getFaredescription());
            map.put("Formula", Formula[i]);
            map.put("col", i+1);
            ls.add(map); 
        }
        dataMap.put("ls",ls);
        ServletContext application = req.getSession().getServletContext();
        /*********輸出圖片未解決********************/
        String a=application.getRealPath("imgs");
        String img = getImageStr(a+"/ceit.png");
        dataMap.put("image", img);
        /***********************************/
        String  templateName = "excel.ftl";   //模板名稱
        java.text.DateFormat format1 = new java.text.SimpleDateFormat("yyyy-MM-dd");
        String exportexcel = application.getRealPath("template")+format1.format(new Date())+ ".xls";
        ExportExcelService.export(templateName, dataMap, exportexcel, "每周報銷單("+format1.format(new Date())+").xls",req,resp);
        
    }
    /***************獲取日期是星期幾*************************/
    public  static  int  dayForWeek(String pTime) throws  Exception {   
        SimpleDateFormat format = new  SimpleDateFormat("yyyy-MM-dd" );   
         Calendar c = Calendar.getInstance();   
         c.setTime(format.parse(pTime));   
         int  dayForWeek = 0 ;   
         if (c.get(Calendar.DAY_OF_WEEK) == 1 ){   
          dayForWeek = 7 ;   
         }else {   
          dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1 ;   
         }   
         return  dayForWeek;   
        }
    /**************將圖片轉成base64********************/
    public String getImageStr(String imgFile) {
        InputStream in = null;
        String da="";
        byte[] data = null;
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
             da=new String(Base64.encodeBase64(data),"UTF-8");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
        e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return da;

    }

}

FTL指令常用標簽及語法

注意:使用freemaker,要求所有標簽必須閉合,否則會導致freemaker無法解析。

freemaker注釋:<#– 注釋內容 –>格式部分,不會輸出

———————————- 基礎語法 ———————————-

1、字符輸出

${emp.name?if_exists}        // 變量存在,輸出該變量,否則不輸出
${emp.name!}              // 變量存在,輸出該變量,否則不輸出
${emp.name?default("xxx")}        // 變量不存在,取默認值xxx  
${emp.name!"xxx"}            // 變量不存在,取默認值xxx

常用內部函數:

${"123<br>456"?html}      // 對字符串進行HTML編碼,對html中特殊字符進行轉義    
${"str"?cap_first}        // 使字符串第一個字母大寫     
${"Str"?lower_case}        // 將字符串轉換成小寫     
${"Str"?upper_case}        // 將字符串轉換成大寫    
${"str"?trim}              // 去掉字符串前后的空白字符   

字符串的兩種拼接方式拼接:

$ { “你好$ {emp.name!}”} //輸出你好+變量名  
$ {“hello”+ emp.name!} //使用+號來連接,輸出你好+變量名

可以通過如下語法來截取子串:

<#assign str =“abcdefghijklmn”/>
//方法1
$ {str?substring(0,4)} //輸出abcd
//方法2 
$ { str [ 0 ] } $ {str [4]} //結果是ae
$ {str [1..4]} //結果是bcde
//返回指定字符的索引
$ {str?index_of("n")}

2,日期輸出

$ {emp.date?string('yyyy -MM-dd')} //日期格式

3,數字輸出(以數字20為例)

$ {emp.name?string.number} //輸出20  
$ {emp.name?string.currency} //¥20.00  
$ {emp.name?string.percent} // 20%  
$ {1.222?int} //將小數轉為int,輸出1  

<#setting number_format =“percent”/> //設置數字默認輸出方式('percent',百分比) 
<#assign answer = 42 /> //聲明變量回答42  
#{answer} //輸出4,200%
$ {answer?string} //輸出4,200%
$ {answer?string.number} //輸出42
$ {answer?string.currency} //輸出¥42.00 
$ {answer?string.percent} //輸出4,200%
#{answer} //輸出42 

數字格式化插值可采用#{expr; format}形式來格式化數字,其中格式可以是:
mX:小數部分最小X位
MX:小數部分最大X位
如下面的例子:
<#assign x = 2.582 /> <#assign y = 4 /> 
# {x; M2} //輸出2.58 
# {y; M2} //輸出4 
# {x; m2} //輸出2.58 
#{Y; m2} //輸出4.0
# {x; m1M2} //輸出2.58 
# {x; m1M2} //輸出4.0 

4,申明變量

<#assign foo = false /> //聲明變量,插入布爾值進行顯示,注意不要用引號
$ {foo?string(“yes”,“no”)} //當為真時輸出“yes”,否則輸出“no”   

申明變量的幾種方式

<#assign name = value> 
<#assign name1 = value1 name2 = value2 ... nameN = valueN> 
<#assign same as above... in namespacehash> 

<#assign name>
 capture this 
</#assign> 

<#assign name in namespacehash> 
capture this 
</#assign> 

5,比較運算算符

表達式中支持的比較運算符符如下幾個:
=或==:判斷兩個值是否相等。
!=:判斷兩個值是否不等。
>或gt:判斷左邊值是否大於右邊值>
<=或lte:判斷左邊值是否小於等於右邊值

6,算術運算符

FreeMarker表達式中完全支持算術運算,
FreeMarker支持的算術運算符包括:+, - ,*,/,%
注意:
(1)運算符兩邊必須是數字
(2)使用+運算符時,如果一邊是數字,一邊是字符串,就會自動將數字轉換為字符串再連接,
     如:$ {3 +“5”},結果是:35 

7,邏輯運算符

邏輯運算符有如下幾個:
邏輯與:&& 
邏輯或:|| 
邏輯非:!
邏輯運算符只能作用於布爾值,否則將產生錯誤

8,FreeMarker中的運算符優先級如下(由高到低排列)

①,一元運算符:!
②,內建函數:
③,乘除法:*,/,%
④,加減法: - ,+ 
⑤,比較:>,<,> =,<=(lt,lte,gt,gte)
⑥,相等:==,=, != 
⑦,邏輯與:&& 
⑧,邏輯或:|| 
⑨,數字范圍:.. 實際上,我們在開發過程中應該使用括號來嚴格區分,這樣的可讀性好,出錯少

9,if邏輯判斷(注意:elseif不加空格)

<#if condition>
...
<#elseif condition2>
...
<#elseif condition3>
...
<#else>
...
</#if>
if 空值判斷

// 當 photoList 不為空時
<#if photoList??>...</#if> 

值得注意的是,${..}只能用於文本部分,不能用於表達式,下面的代碼是錯誤的:
<#if ${isBig}>Wow!</#if>
<#if "${isBig}">Wow!</#if>

// 正確寫法
<#if isBig>Wow!</#if> 

10、switch (條件可為數字,可為字符串)

<#switch value> 
<#case refValue1> 
....
<#break> 
<#case refValue2> 
....
<#break> 
<#case refValueN> 
....
<#break> 
<#default> 
.... 
</#switch>

11、集合 & 循環

// 遍歷集合:
<#list empList! as emp> 
    ${emp.name!}
</#list>

// 可以這樣遍歷集合:
<#list 0..(empList!?size-1) as i>
    ${empList[i].name!}
</#list>

// 與jstl循環類似,也可以訪問循環的狀態。

empList?size    // 取集合的長度
emp_index:     // int類型,當前對象的索引值 
emp_has_next:     // boolean類型,是否存在下一個對象

// 使用<#break>跳出循環
<#if emp_index = 0><#break></#if>

// 集合長度判斷 
<#if empList?size != 0></#if> // 判斷=的時候,注意只要一個=符號,而不是==

<#assign l=0..100/>    // 定義一個int區間的0~100的集合,數字范圍也支持反遞增,如100..2
<#list 0..100 as i>   // 等效於java for(int i=0; i <= 100; i++)
  ${i}
</#list>

// 截取子集合:
empList[3..5] //返回empList集合的子集合,子集合中的元素是empList集合中的第4-6個元素

// 創建集合:
<#list ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期天"] as x>

// 集合連接運算,將兩個集合連接成一個新的集合
<#list ["星期一","星期二","星期三"] + ["星期四","星期五","星期六","星期天"] as x>

// 除此之外,集合元素也可以是表達式,例子如下:
[2 + 2, [1, 2, 3, 4], "whatnot"]

// seq_contains:判斷序列中的元素是否存在
<#assign x = ["red", 16, "blue", "cyan"]> 
${x?seq_contains("blue")?string("yes", "no")}    // yes
${x?seq_contains("yellow")?string("yes", "no")}  // no
${x?seq_contains(16)?string("yes", "no")}        // yes
${x?seq_contains("16")?string("yes", "no")}      // no

// seq_index_of:第一次出現的索引
<#assign x = ["red", 16, "blue", "cyan", "blue"]> 
${x?seq_index_of("blue")}  // 2

// sort_by:排序(升序)
<#list movies?sort_by("showtime") as movie></#list>

// sort_by:排序(降序)
<#list movies?sort_by("showtime")?reverse as movie></#list>

// 具體介紹:
// 不排序的情況:
<#list movies as moive>
  <a href="${moive.url}">${moive.name}</a>
</#list>

//要是排序,則用
<#list movies?sort as movie>
  <a href="${movie.url}">${movie.name}</a>
</#list>

// 這是按元素的首字母排序。若要按list中對象元素的某一屬性排序的話,則用
<#list moives?sort_by(["name"]) as movie>
  <a href="${movie.url}">${movie.name}</a>
</#list>

//這個是按list中對象元素的[name]屬性排序的,是升序,如果需要降序的話,如下所示:
<#list movies?sort_by(["name"])?reverse as movie>
  <a href="${movie.url}">${movie.name}</a>
</#list>

12、Map對象

// 創建map
<#assign scores = {"語文":86,"數學":78}>

// Map連接運算符
<#assign scores = {"語文":86,"數學":78} + {"數學":87,"Java":93}>

// Map元素輸出
emp.name       // 全部使用點語法
emp["name"]    // 使用方括號
循環//遍歷集合:<#list empList!as emp>     $ {emp.name!}

13、FreeMarker支持如下轉義字符:

\" :雙引號(u0022)
\' :單引號(u0027)
\\ :反斜杠(u005C)
\n :換行(u000A)
\r :回車(u000D)
\t :Tab(u0009)
\b :退格鍵(u0008)
\f :Form feed(u000C)
\l :<
\g :>
\a :&
\{ :{
\xCode :直接通過4位的16進制數來指定Unicode碼,輸出該unicode碼對應的字符.

如果某段文本中包含大量的特殊符號,FreeMarker提供了另一種特殊格式:可以在指定字符串內容的引號前增加r標記,在r標記后的文件將會直接輸出.看如下代碼:
${r"${foo}"} // 輸出 ${foo}
${r"C:/foo/bar"} // 輸出 C:/foo/bar

14、include指令

// include指令的作用類似於JSP的包含指令:
<#include "/test.ftl" encoding="UTF-8" parse=true>

// 在上面的語法格式中,兩個參數的解釋如下:
encoding="GBK"  // 編碼格式
parse=true    // 是否作為ftl語法解析,默認是true,false就是以文本方式引入
注意:在ftl文件里布爾值都是直接賦值的如parse=true,而不是parse="true"

15、import指令

// 類似於jsp里的import,它導入文件,然后就可以在當前文件里使用被導入文件里的宏組件
<#import "/libs/mylib.ftl" as my>
// 上面的代碼將導入/lib/common.ftl模板文件中的所有變量,交將這些變量放置在一個名為com的Map對象中,"my"在freemarker里被稱作namespace

16、compress 壓縮

// 用來壓縮空白空間和空白的行 
<#compress> 
    ... 
</#compress>
<#t> // 去掉左右空白和回車換行 

<#lt>// 去掉左邊空白和回車換行 

<#rt>// 去掉右邊空白和回車換行 

<#nt>// 取消上面的效果

17、escape,noescape 對字符串進行HTML編碼

// escape指令導致body區的插值都會被自動加上escape表達式,但不會影響字符串內的插值,
    只會影響到body內出現的插值,使用escape指令的語法格式如下:
<#escape x as x?html> 
  First name: ${firstName} 
<#noescape>Last name: ${lastName}</#noescape> 
  Maiden name: ${maidenName} 
</#escape>

// 相同表達式
First name: ${firstName?html} 
Last name: ${lastName} 
Maiden name: ${maidenName?html}

———————————- 高級語法 ———————————-

1、global全局賦值語法

<#global name=value> 

<#global name1=value1 name2=value2 ... nameN=valueN> 

<#global name> 
  capture this 
</#global>

// 利用這個語法給變量賦值,那么這個變量在所有的namespace中是可見的,
    如果這個變量被當前的assign語法覆蓋如<#global x=2><#assign x=1>
    在當前頁面里x=2將被隱藏,或者通過${.globals.x} 來訪問

2、setting 語法

// 用來設置整個系統的一個環境 
locale // zh_CN 中文環境
number_format 
boolean_format 
date_format , time_format , datetime_format 
time_zone 
classic_compatible
// 例1:
<#setting number_format="percent"/>    // 設置數字默認輸出方式('percent',百分比)

// 例2:
// 假如當前是匈牙利的設置,然后修改成美國
${1.2} // 輸出1,2
<#setting locale="en_US"> 
${1.2} // 輸出1.2,因為匈牙利是采用", "作為十進制的分隔符,美國是用". "

3、macro宏指令

例子1:

<#-- 定義宏 -->
<#macro test foo bar="Bar" baaz=-1> 
  Text: ${foo}, ${bar}, ${baaz}
</#macro>

<#-- 使用宏 -->
<@test foo="a" bar="b" baaz=5*5/>  // 輸出:Text: a, b, 25
<@test foo="a" bar="b"/>        // 輸出:Text: a, b, -1
<@test foo="a" baaz=5*5-2/>     // 輸出:Text: a, Bar, 23
<@test foo="a"/>                   // 輸出:Text: a, Bar, -1

例子2:

<#-- 定義一個循環輸出的宏 -->
<#macro list title items> 
  ${title}
  <#list items as x>
    *${x}
  </#list> 
</#macro> 

<#-- 使用宏 -->
<@list items=["mouse", "elephant", "python"] title="Animals"/>
// 輸出Animals *mouse *elephant *python

例子3:

<#-- 嵌套宏 -->
<#macro border>
  <table>
    <#nested>
  </table>
</#macro>

<#-- 嵌套宏使用 -->
<@border>
  <tr><td>hahaha</td></tr>
</@border> 
輸出結果:
<table>
  <tr><td>hahaha</td></tr>
</table>

例子4:在nested指令中使用循環變量時,可以使用多個循環變量,看如下代碼

<#-- 循環嵌套宏 -->
<#macro repeat count>
  <#list 1..count as x>
    <#nested x, x/2, x==count> // 使用nested指令時指定了三個循環變量
  </#list>
</#macro>

<#-- 使用宏 -->
<@repeat count = 4; c, halfc, last>
  ${c}. ${halfc}<#if last> Last!</#if>
</@repeat>
// 輸出結果:
// 1. 0.5
// 2. 1
// 3. 1.5
// 4. 2 Last!
freemarker 宏嵌套nested 的使用:
http://blog.sina.com.cn/s/blog_7e5699790100z59g.html  

4、結束macro指令

// return指令用於結束macro指令
<#-- 創建宏 -->
<#macro book>
  spring
  <#return>
  j2ee
</#macro>

<#-- 使用宏 -->
<@book />
// 上面的代碼輸出:spring,而j2ee位於return指令之后,不會輸出.

工具類http://files.cnblogs.com/files/duke-cui/FreeMarkerUtil.rar


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM