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.加载模板
        //创建核心配置对象
        Configuration config = new Configuration(Configuration.VERSION_2_3_28);
        //设置加载的目录,在FreemarkerSample1.class包中加载,ftl文件,空代表当前路径
        config.setClassForTemplateLoading(FreemarkerSample1.class, "");
        //得到模板对象
        Template t = config.getTemplate("sample1.ftl");
        //2.创建数据
        Map data = new HashMap();
        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.产生输出
        //System.out输出的是字节流,process输出的是字符流,因此需要进行转换
        t.process(data,new OutputStreamWriter(System.out));
    }

}
//sample1.ftl
<#-- Freemarker取值 -->
${site}-${url}
<#-- !默认值 -->
${author!"不存在的属性"}
<#-- ?string 格式化输出 -->
${date?string("yyyy年MM月dd日 HH:mm:ss SSS")}
${number}
${number?string("0.00")}
<#-- 输出对象 -->
SN:${computer.sn}
型号:${computer.model}
配置信息:${computer.info["cpu"]}
配置信息:${computer.info.cpu}

<#if computer.state == 1>
状态:正在使用
<#elseif computer.state == 2>
状态:闲置
<#elseif computer.state == 3>
状态:已作废
<#else>
状态:无效状态


<#if computer.user??> <#-- 判断不为空 true不为空 -->
用户:${computer.user}


<#if computer.sn == "1234567"> <#-- 字符串相等 用 == -->
重要设备



<#switch computer.state>
    <#case 1>
        状态:正在使用
        <#break>
    <#case 2>
        状态:闲置
        <#break>
    <#case 3>
        状态:已作废
        <#break>
    <#default>
        状态:无效状态

//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.加载模板
        //创建核心配置对象
        Configuration config = new Configuration(Configuration.VERSION_2_3_28);
        //设置加载的目录,在FreemarkerSample1.class包中加载,ftl文件,空代表当前路径
        config.setClassForTemplateLoading(FreemarkerSample2.class, "");
        //得到模板对象
        Template t = config.getTemplate("sample2.ftl");
        //2.创建数据
        Map data = new HashMap();
        List 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 可以保证数据按存放顺序进行提取
        Map computerMap = new LinkedHashMap();
        for(Computer c : computers) {
            computerMap.put(c.getSn(), c);
        }
        data.put("computers_map", computerMap);
        //3.产生输出
        //System.out输出的是字节流,process输出的是字符流,因此需要进行转换
        t.process(data,new OutputStreamWriter(System.out));
    }

}
//sample2.ftl
<#list computers as c>
序号:${c_index + 1} <#-- 循环索引 -->
SN:${c.sn}
型号:${c.model}
状态:${c.state}
用户:${c.user}
采购日期:${c.dop?string("yyyy-MM-dd")}
采购价格:${c.price?string("0.00")}

======================================================

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

2.内建函数

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.加载模板
        //创建核心配置对象
        Configuration config = new Configuration(Configuration.VERSION_2_3_28);
        //设置加载的目录,在FreemarkerSample1.class包中加载,ftl文件,空代表当前路径
        config.setClassForTemplateLoading(FreemarkerSample3.class, "");
        //得到模板对象
        Template t = config.getTemplate("sample3.ftl");
        //2.创建数据
        Map data = new HashMap();
        data.put("name", "jackson");
        data.put("brand", "bmw");
        data.put("words", "first blood");
        data.put("n",37981.83);
        data.put("data", new Date());
        List 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 可以保证数据按存放顺序进行提取
        Map computerMap = new LinkedHashMap();
        for(Computer c : computers) {
            computerMap.put(c.getSn(), c);
        }
        data.put("computers_map", computerMap);
        //3.产生输出
        //System.out输出的是字节流,process输出的是字符流,因此需要进行转换
        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三目运算 -->

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

公司共有${computers?size}台电脑
第一台:${computers?first.model}
最后一台${computers?last.model}

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


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


<#-- freemarker.foofun.cn  查询更多内建函数-->

freemarker.foofun.cn 查询更多内建函数

3.freemarker与servlet联动

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,"张三","市场部","客户代表",8000f));
        list.add(new Employee(8871,"李四","研发部","运维工程师",7000f));
        list.add(new Employee(7732,"王五","市场部","客户代表",8000f));
        request.setAttribute("employee_list", list);
        //利用转发进行跳转
        request.getRequestDispatcher("/employee.ftl").forward(request, response);
        
    }

}
//employee.ftl




    
    
    员工列表
    
    
    
    

    



IMOOC员工信息表

<#-- 注意,对 employee_list进行属性获取时,依次自动从request session context 域中查找属性 --> <#list employee_list as emp>
序号 员工编号 姓名 部门 职务 工资  
${emp_index + 1} ${emp.empno?string("0")} ${emp.ename} ${emp.department} ${emp.job} ¥${emp.salary?string("0.00")}

html代码写在ftl文件中

//web.xml


  fm-web
  
    index.html
    index.htm
    index.jsp
    default.html
    default.htm
    default.jsp
  
  
    freemarker
    freemarker.ext.servlet.FreemarkerServlet
    
        TemplatePath
        /WEB-INF/ftl
    
  
  
    freemarker
    *.ftl
  

你可能感兴趣的:(40.模板引擎与Freemarker)