注意這里是普通的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ù)
//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)
//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> </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>