40.模板引擎與Freemarker

image.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png

文件目錄

image.png

注意這里是普通的java類杠览,再lib文件中添加了jar后杨耙,需要右鍵build path -> add ..path



//FreemarkerSample1.java
package com.imooc.freemarker;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.imooc.freemarker.entity.Computer;

import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;

public class FreemarkerSample1 {

    public static void main(String[] args) throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException, TemplateException {
        // TODO Auto-generated method stub
        //1.加載模板
        //創(chuàng)建核心配置對(duì)象
        Configuration config = new Configuration(Configuration.VERSION_2_3_28);
        //設(shè)置加載的目錄,在FreemarkerSample1.class包中加載,ftl文件棚放,空代表當(dāng)前路徑
        config.setClassForTemplateLoading(FreemarkerSample1.class, "");
        //得到模板對(duì)象
        Template t = config.getTemplate("sample1.ftl");
        //2.創(chuàng)建數(shù)據(jù)
        Map<String,Object> data = new HashMap<String,Object>();
        data.put("site","百度");
        data.put("url","http://www.baidu.com");
        data.put("date",new Date());
        data.put("number",837183.88833);
        Map info = new HashMap();
        info.put("cpu", "i5");
        Computer c1 = new Computer("1234567","Thinkpad",1,"李四",new Date(),12900f,info);
        data.put("computer",c1);
        //3.產(chǎn)生輸出
        //System.out輸出的是字節(jié)流,process輸出的是字符流,因此需要進(jìn)行轉(zhuǎn)換
        t.process(data,new OutputStreamWriter(System.out));
    }

}
//sample1.ftl
<#-- Freemarker取值 -->
${site}-${url}
<#-- 梅垄!默認(rèn)值 -->
${author!"不存在的屬性"}
<#-- ?string 格式化輸出 -->
${date?string("yyyy年MM月dd日 HH:mm:ss SSS")}
${number}
${number?string("0.00")}
<#-- 輸出對(duì)象 -->
SN:${computer.sn}
型號(hào):${computer.model}
配置信息:${computer.info["cpu"]}
配置信息:${computer.info.cpu}

<#if computer.state == 1>
狀態(tài):正在使用
<#elseif computer.state == 2>
狀態(tài):閑置
<#elseif computer.state == 3>
狀態(tài):已作廢
<#else>
狀態(tài):無(wú)效狀態(tài)
</#if>

<#if computer.user??> <#-- 判斷不為空 true不為空 -->
用戶:${computer.user}
</#if>

<#if computer.sn == "1234567"> <#-- 字符串相等 用 == -->
重要設(shè)備
</#if>


<#switch computer.state>
    <#case 1>
        狀態(tài):正在使用
        <#break>
    <#case 2>
        狀態(tài):閑置
        <#break>
    <#case 3>
        狀態(tài):已作廢
        <#break>
    <#default>
        狀態(tài):無(wú)效狀態(tài)
</#switch>
//FreemarkerSample2.java
package com.imooc.freemarker;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.imooc.freemarker.entity.Computer;

import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;

public class FreemarkerSample2 {

    public static void main(String[] args) throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException, TemplateException {
        // TODO Auto-generated method stub
        //1.加載模板
        //創(chuàng)建核心配置對(duì)象
        Configuration config = new Configuration(Configuration.VERSION_2_3_28);
        //設(shè)置加載的目錄,在FreemarkerSample1.class包中加載,ftl文件输玷,空代表當(dāng)前路徑
        config.setClassForTemplateLoading(FreemarkerSample2.class, "");
        //得到模板對(duì)象
        Template t = config.getTemplate("sample2.ftl");
        //2.創(chuàng)建數(shù)據(jù)
        Map<String,Object> data = new HashMap<String,Object>();
        List<Computer> computers = new ArrayList();
        computers.add(new Computer("1234567","Thinkpad1",1,"李四1",new Date(),12900f,new HashMap()));
        computers.add(new Computer("1234568","Thinkpad2",1,"李四2",new Date(),12900f,new HashMap()));
        computers.add(new Computer("1234569","Thinkpad3",1,"李四3",new Date(),12900f,new HashMap()));
        computers.add(new Computer("1234570","Thinkpad4",1,"李四4",new Date(),12900f,new HashMap()));
        computers.add(new Computer("1234571","Thinkpad5",1,"李四5",new Date(),12900f,new HashMap()));
        data.put("computers",computers);
        //LinkedHashMap 可以保證數(shù)據(jù)按存放順序進(jìn)行提取
        Map computerMap = new LinkedHashMap();
        for(Computer c : computers) {
            computerMap.put(c.getSn(), c);
        }
        data.put("computers_map", computerMap);
        //3.產(chǎn)生輸出
        //System.out輸出的是字節(jié)流队丝,process輸出的是字符流,因此需要進(jìn)行轉(zhuǎn)換
        t.process(data,new OutputStreamWriter(System.out));
    }

}
//sample2.ftl
<#list computers as c>
序號(hào):${c_index + 1} <#-- 循環(huán)索引 -->
SN:${c.sn}
型號(hào):${c.model}
狀態(tài):${c.state}
用戶:${c.user}
采購(gòu)日期:${c.dop?string("yyyy-MM-dd")}
采購(gòu)價(jià)格:${c.price?string("0.00")}
</#list>
======================================================

<#list computers_map?keys as k>
${k} - ${computers_map[k].model}
${computers_map[k].price?string("0.00")}
</#list>

2.內(nèi)建函數(shù)

image.png
//FreemarkerSample3 .java
package com.imooc.freemarker;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.imooc.freemarker.entity.Computer;

import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;

public class FreemarkerSample3 {

    public static void main(String[] args) throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException, TemplateException {
        // TODO Auto-generated method stub
        //1.加載模板
        //創(chuàng)建核心配置對(duì)象
        Configuration config = new Configuration(Configuration.VERSION_2_3_28);
        //設(shè)置加載的目錄,在FreemarkerSample1.class包中加載欲鹏,ftl文件机久,空代表當(dāng)前路徑
        config.setClassForTemplateLoading(FreemarkerSample3.class, "");
        //得到模板對(duì)象
        Template t = config.getTemplate("sample3.ftl");
        //2.創(chuàng)建數(shù)據(jù)
        Map<String,Object> data = new HashMap<String,Object>();
        data.put("name", "jackson");
        data.put("brand", "bmw");
        data.put("words", "first blood");
        data.put("n",37981.83);
        data.put("data", new Date());
        List<Computer> computers = new ArrayList();
        computers.add(new Computer("1234567","Thinkpad1",1,"李四1",new Date(),12900f,new HashMap()));
        computers.add(new Computer("1234568","Thinkpad2",1,"李四2",new Date(),12900f,new HashMap()));
        computers.add(new Computer("1234569","Thinkpad3",1,"李四3",new Date(),12900f,new HashMap()));
        computers.add(new Computer("1234570","Thinkpad4",1,"李四4",new Date(),12900f,new HashMap()));
        computers.add(new Computer("1234571","Thinkpad5",1,"李四5",new Date(),12900f,new HashMap()));
        data.put("computers",computers);
        //LinkedHashMap 可以保證數(shù)據(jù)按存放順序進(jìn)行提取
        Map computerMap = new LinkedHashMap();
        for(Computer c : computers) {
            computerMap.put(c.getSn(), c);
        }
        data.put("computers_map", computerMap);
        //3.產(chǎn)生輸出
        //System.out輸出的是字節(jié)流,process輸出的是字符流赔嚎,因此需要進(jìn)行轉(zhuǎn)換
        t.process(data,new OutputStreamWriter(System.out));
    }

}
//sample3.ftl
${name?cap_first}
${brand?upper_case}
${brand?length}
${words?replace("blood","*****")}
${words?index_of("blood")}
${(words?index_of("blood") != -1)?string("包含敏感詞匯","不包含敏感詞匯")} <#--  string三目運(yùn)算 -->

${n?round} <#-- 四舍五入 -->
${n?floor} <#-- 下取整 -->
${n?ceiling} <#-- 上取整 -->

公司共有${computers?size}臺(tái)電腦
第一臺(tái):${computers?first.model}
最后一臺(tái)${computers?last.model}

<#list computers?sort_by("price") as c> <#-- 升序 -->
    ${c.sn} - ${c.price}
</#list>

<#list computers?sort_by("price")?reverse as c> <#-- 降序 -->
    ${c.sn} - ${c.price}
</#list>

<#-- freemarker.foofun.cn  查詢更多內(nèi)建函數(shù)-->

freemarker.foofun.cn 查詢更多內(nèi)建函數(shù)

3.freemarker與servlet聯(lián)動(dòng)

image.png
//Employee.java
package com.imooc.freemarker.servlet;

public class Employee {
    private Integer empno;
    private String ename;
    private String department;
    private String job;
    private Float salary;
    public Employee(Integer empno, String ename, String department, String job, Float salary) {
        super();
        this.empno = empno;
        this.ename = ename;
        this.department = department;
        this.job = job;
        this.salary = salary;
    }
    public Employee() {
        super();
    }
    public Integer getEmpno() {
        return empno;
    }
    public void setEmpno(Integer empno) {
        this.empno = empno;
    }
    public String getEname() {
        return ename;
    }
    public void setEname(String ename) {
        this.ename = ename;
    }
    public String getDepartment() {
        return department;
    }
    public void setDepartment(String department) {
        this.department = department;
    }
    public String getJob() {
        return job;
    }
    public void setJob(String job) {
        this.job = job;
    }
    public Float getSalary() {
        return salary;
    }
    public void setSalary(Float salary) {
        this.salary = salary;
    }
    
}

//ListServlet.java
package com.imooc.freemarker.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ListServlet
 */
@WebServlet("/list")
public class ListServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ListServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List list = new ArrayList();
        list.add(new Employee(7731,"張三","市場(chǎng)部","客戶代表",8000f));
        list.add(new Employee(8871,"李四","研發(fā)部","運(yùn)維工程師",7000f));
        list.add(new Employee(7732,"王五","市場(chǎng)部","客戶代表",8000f));
        request.setAttribute("employee_list", list);
        //利用轉(zhuǎn)發(fā)進(jìn)行跳轉(zhuǎn)
        request.getRequestDispatcher("/employee.ftl").forward(request, response);
        
    }

}
//employee.ftl

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>員工列表</title>
    <link href="css/bootstrap.css" type="text/css" rel="stylesheet"></link>
    
    <script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
    <script type="text/javascript" src="js/bootstrap.js"></script>

    <style type="text/css">
        .pagination {
            margin: 0px
        }

        .pagination > li > a, .pagination > li > span {
            margin: 0 5px;
            border: 1px solid #dddddd;
        }

        .glyphicon {
            margin-right: 3px;
        }

        .form-control[readonly] {
            cursor: pointer;
            background-color: white;
        }
        #dlgPhoto .modal-body{
            text-align: center;
        }
        .preview{

            max-width: 500px;
        }
    </style>
</head>
<body>

<div class="container">
    <div class="row">
        <h1 style="text-align: center">IMOOC員工信息表</h1>
        <div class="panel panel-default">
            <div class="clearfix panel-heading ">
                <div class="input-group" style="width: 500px;">
                    
                </div>
            </div>

            <table class="table table-bordered table-hover">
                <thead>
                <tr>
                    <th>序號(hào)</th>
                    <th>員工編號(hào)</th>
                    <th>姓名</th>
                    <th>部門</th>
                    <th>職務(wù)</th>
                    <th>工資</th>
                    <th>&nbsp;</th>
                </tr>
                </thead>
                <tbody>
                <#-- 注意膘盖,對(duì) employee_list進(jìn)行屬性獲取時(shí),依次自動(dòng)從request session context 域中查找屬性 -->
                <#list employee_list as emp>
                    <tr>
                    <td>${emp_index + 1}</td>
                    <td>${emp.empno?string("0")}</td>
                    <td>${emp.ename}</td>
                    <td>${emp.department}</td>
                    <td>${emp.job}</td>
                    <td style="color: red;font-weight: bold">¥${emp.salary?string("0.00")}</td>     
                </tr>
                </#list>
                
                
                </tbody>
            </table>
        </div>
    </div>
</div>

</body>
</html>

html代碼寫在ftl文件中

//web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>fm-web</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>freemarker</servlet-name>
    <servlet-class>freemarker.ext.servlet.FreemarkerServlet</servlet-class>
    <init-param>
        <param-name>TemplatePath</param-name>
        <param-value>/WEB-INF/ftl</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>freemarker</servlet-name>
    <url-pattern>*.ftl</url-pattern>
  </servlet-mapping>
</web-app>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末尤误,一起剝皮案震驚了整個(gè)濱河市侠畔,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌损晤,老刑警劉巖践图,帶你破解...
    沈念sama閱讀 212,884評(píng)論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異沉馆,居然都是意外死亡码党,警方通過(guò)查閱死者的電腦和手機(jī)德崭,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,755評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)揖盘,“玉大人眉厨,你說(shuō)我怎么就攤上這事∈尴粒” “怎么了憾股?”我有些...
    開(kāi)封第一講書人閱讀 158,369評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)箕慧。 經(jīng)常有香客問(wèn)我服球,道長(zhǎng),這世上最難降的妖魔是什么颠焦? 我笑而不...
    開(kāi)封第一講書人閱讀 56,799評(píng)論 1 285
  • 正文 為了忘掉前任斩熊,我火速辦了婚禮,結(jié)果婚禮上伐庭,老公的妹妹穿的比我還像新娘粉渠。我一直安慰自己,他們只是感情好圾另,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,910評(píng)論 6 386
  • 文/花漫 我一把揭開(kāi)白布霸株。 她就那樣靜靜地躺著,像睡著了一般集乔。 火紅的嫁衣襯著肌膚如雪去件。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書人閱讀 50,096評(píng)論 1 291
  • 那天扰路,我揣著相機(jī)與錄音箫攀,去河邊找鬼。 笑死幼衰,一個(gè)胖子當(dāng)著我的面吹牛靴跛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播渡嚣,決...
    沈念sama閱讀 39,159評(píng)論 3 411
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼梢睛,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了识椰?” 一聲冷哼從身側(cè)響起绝葡,我...
    開(kāi)封第一講書人閱讀 37,917評(píng)論 0 268
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎腹鹉,沒(méi)想到半個(gè)月后藏畅,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,360評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,673評(píng)論 2 327
  • 正文 我和宋清朗相戀三年愉阎,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了绞蹦。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,814評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡榜旦,死狀恐怖幽七,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情溅呢,我是刑警寧澤澡屡,帶...
    沈念sama閱讀 34,509評(píng)論 4 334
  • 正文 年R本政府宣布,位于F島的核電站咐旧,受9級(jí)特大地震影響驶鹉,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜铣墨,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,156評(píng)論 3 317
  • 文/蒙蒙 一室埋、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧踏兜,春花似錦、人聲如沸八秃。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 30,882評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)昔驱。三九已至疹尾,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間骤肛,已是汗流浹背纳本。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 32,123評(píng)論 1 267
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留腋颠,地道東北人繁成。 一個(gè)月前我還...
    沈念sama閱讀 46,641評(píng)論 2 362
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像淑玫,于是被迫代替她去往敵國(guó)和親巾腕。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,728評(píng)論 2 351

推薦閱讀更多精彩內(nèi)容