Java操作FreeMarker模板引擎的基本用法示例小結(jié)
FreeMarker 是一個(gè)采用 Java 開(kāi)發(fā)的模版引擎,是一個(gè)基于模版生成文本的通用工具。 它被設(shè)計(jì)用來(lái)生成 HTML Web 頁(yè)面,特別是基于 MVC 模式的應(yīng)用程序。雖然使用FreeMarker需要具有一些編程的能力,但通常由 Java 程序準(zhǔn)備要顯示的數(shù)據(jù),由 FreeMarker 生成頁(yè)面,并通過(guò)模板顯示準(zhǔn)備的數(shù)據(jù)。
http://freemarker.org/
public void process(String template, Map<String, ?> data) throws Exception { Configuration cfg = new Configuration(); cfg.setDirectoryForTemplateLoading(new File("ftl")); cfg.setObjectWrapper(new DefaultObjectWrapper()); //設(shè)置字符集 cfg.setDefaultEncoding("UTF-8"); //設(shè)置尖括號(hào)語(yǔ)法和方括號(hào)語(yǔ)法,默認(rèn)是自動(dòng)檢測(cè)語(yǔ)法 // 自動(dòng) AUTO_DETECT_TAG_SYNTAX // 尖括號(hào) ANGLE_BRACKET_TAG_SYNTAX // 方括號(hào) SQUARE_BRACKET_TAG_SYNTAX cfg.setTagSyntax(Configuration.AUTO_DETECT_TAG_SYNTAX); Writer out = new OutputStreamWriter(new FileOutputStream(FILE_DIR + template + ".txt"),"UTF-8"); Template temp = cfg.getTemplate(template); temp.process(data, out); out.flush(); }
0、使用freemarker制作HelloWord web頁(yè)面
新建一個(gè)WEB工程,并導(dǎo)入freemarker.jar,在WEB-INF下新建文件夾templates用于存放模版文件,在templates下新建test.ftl,這是示例模版文件。內(nèi)容就是HTML內(nèi)容,里面帶有一個(gè)標(biāo)記符,用于將來(lái)進(jìn)行變量替換,內(nèi)容如下:
<html> <head> <title>freemarker測(cè)試</title> </head> <body> <h1>${message},${name}</h1> </body> </html>
新建一個(gè)Servlet,用于請(qǐng)求設(shè)置變量,并處理模版的輸出:
package com.test.servlet; import java.io.IOException; import java.io.Writer; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; @SuppressWarnings("serial") public class HelloFreeMarkerServlet extends HttpServlet { // 負(fù)責(zé)管理FreeMarker模板的Configuration實(shí)例 private Configuration cfg = null; public void init() throws ServletException { // 創(chuàng)建一個(gè)FreeMarker實(shí)例 cfg = new Configuration(); // 指定FreeMarker模板文件的位置 cfg.setServletContextForTemplateLoading(getServletContext(), "/WEB-INF/templates"); } @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 建立數(shù)據(jù)模型 Map root = new HashMap(); root.put("message", "hello world"); root.put("name", "java小強(qiáng)"); // 獲取模板文件 Template t = cfg.getTemplate("test.ftl"); // 使用模板文件的Charset作為本頁(yè)面的charset // 使用text/html MIME-type response.setContentType("text/html; charset=" + t.getEncoding()); Writer out = response.getWriter(); // 合并數(shù)據(jù)模型和模板,并將結(jié)果輸出到out中 try { t.process(root, out); // 往模板里寫數(shù)據(jù) } catch (TemplateException e) { e.printStackTrace(); } } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void destroy() { super.destroy(); } }
注意要在你的web.xml中配置該Servlet:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>hello</servlet-name> <servlet-class> com.test.servlet.HelloFreeMarkerServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
為了方便測(cè)試,訪問(wèn)工程直接跳轉(zhuǎn)到Servlet,對(duì)主頁(yè)index.jsp做一個(gè)簡(jiǎn)單修改:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName() +":"+request.getServerPort()+path+"/"; %> <html> <body> <% String mypath = "hello"; response.sendRedirect(basePath + mypath); %> </body> </html>
部署工程到Tomcat,啟動(dòng)并訪問(wèn)http://localhost:8080/f ,這里我建立的工程名稱就是 f 。
1、計(jì)算式
<#-- 1、算術(shù)運(yùn)算 -->[BR] ${3 + 4} <#-- 2、內(nèi)建函數(shù) -->[BR] ${"rensanning"?upper_case}
2、輸出一個(gè)值
HashMap t2root = new HashMap<String, String>(); t2root.put("user", "RenSanNing"); ${user}, Welcome!
3、輸出一個(gè)列表
Map<String, Object> t3root = new HashMap<String, Object>(); List<Food> menu = new ArrayList<Food>(); menu.add(new Food("iText in Action", 98)); menu.add(new Food("iBATIS in Action", 118)); menu.add(new Food("Lucene in Action", 69)); t3root.put("menu", menu); <#list menu as food> ${food.name} ${food.price?string.currency} </#list>
4、邏輯判斷(IF,SWITCH)
Map<String, Object> t4root = new HashMap<String, Object>(); t4root.put("x", 2); t4root.put("y", "medium");
<1>if, else, elseif: <#if x == 1> x is 1 <#elseif x == 2> x is 2 <#elseif x == 3> x is 3 <#elseif x == 4> x is 4 <#else> x is not 1 nor 2 nor 3 nor 4 </#if> <2>switch, case, default, break: <#switch y> <#case "small"> This will be processed if it is small <#break> <#case "medium"> This will be processed if it is medium <#break> <#case "large"> This will be processed if it is large <#break> <#default> This will be processed if it is neither </#switch> <3>list, break: <#assign seq = ["winter", "spring", "summer", "autumn"]> <#list seq as x> ${x_index + 1}. ${x}<#if x_has_next>,</#if> </#list>
5、自定義函數(shù)
<#function fact n> <#if n == 0> <#return 1 /> <#else> <#return fact(n - 1) * n /> </#if> </#function> <#list 0..10 as i> ${i}! => ${fact(i)} </#list>
6、定義變量
<#-- 1、本地變量 -->[BR] <#function partg n lst> <#local ans = []> <#list lst as x> <#if (x >= n)> <#local ans = ans + [x]> </#if> </#list> <#return ans> </#function> <#assign ls = [10, 2, 4, 5, 8, 1, 3]> <#list partg(4, ls) as x>${x} </#list> <#-- 2、變量域測(cè)試 -->[BR] <#macro test> 03. ${x} <#global x = "global2"> 04. ${x} <#assign x = "assign2"> 05. ${x} <#local x = "local1"> 06. ${x} <#list ["循環(huán)1"] as x> 07. ${x} <#local x = "local2"> 08. ${x} <#assign x = "assign3"> 09. ${x} </#list> 10. ${x} </#macro> <#global x = "global1" /> 01. ${x} <#assign x = "assign1" /> 02. ${x} <@test /> 11. ${x}
7、定義宏macro
<#-- 1、無(wú)參數(shù) -->[BR] <#macro greet> Welcome! </#macro> <@greet /> <#-- 2、有參數(shù) -->[BR] <#macro greet user> ${user}, Welcome! </#macro> <@greet user="RenSanNing"/> <#-- 3、有多個(gè)參數(shù) -->[BR] <#macro table cols rows> <table> <#list 1..rows as row> <tr> <#list 1..cols as col> <td>${row}, ${col}</td> </#list> </tr> </#list> </table> </#macro> <@table cols=3 rows=2 /> <#-- 4、中間跳出 -->[BR] <#macro out> 顯示文字 <#return> 不顯示文字 </#macro> <@out /> <#-- 5、嵌套 -->[BR] <#macro lprint lst> <#list lst as item> ・${item}<#nested item /> </#list> </#macro> <@lprint 1..3; x>^2 = ${x * x}</@lprint> <@lprint 1..3; x>^3 = ${x * x * x}</@lprint> <@lprint ["Let's go", "to the", "land of Medetai"] />
8、include
<#include "T108include.ftl"> ${url} <@greet name="rensanning" />
T108include.ftl
<#macro greet name> ${name}, Welcome! </#macro> <#assign url="http://www.baidu.com/">
9、名字空間
<#import "T109include.ftl" as my> <#assign url="http://www.google.com/"> ${my.url} <@my.greet name="rensanning" /> ${url}
T109include.ftl
<#macro greet name> ${name}, Welcome! </#macro> <#assign url="http://www.baidu.com/">
10、自定義指令Directive
public class SystemDateDirective implements TemplateDirectiveModel { public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); env.getOut().append(sdf.format(cal.getTime())); } } public class TextCutDirective implements TemplateDirectiveModel { public static final String PARAM_S = "s"; public static final String PARAM_LEN = "len"; public static final String PARAM_APPEND = "append"; @SuppressWarnings("unchecked") public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { String s = getString(PARAM_S, params); Integer len = getInt(PARAM_LEN, params); String append = getString(PARAM_APPEND, params); if (s != null) { Writer out = env.getOut(); if (len != null) { out.append(textCut(s, len, append)); } else { out.append(s); } } }
....
Map<String, Object> t10root = new HashMap<String, Object>(); t10root.put("systemdate", new SystemDateDirective()); t10root.put("text_cut", new TextCutDirective());
- java Spring整合Freemarker的詳細(xì)步驟
- 使用Java進(jìn)行FreeMarker的web模板開(kāi)發(fā)的基礎(chǔ)教程
- 基于Java的Spring框架來(lái)操作FreeMarker模板的示例
- java Freemarker頁(yè)面靜態(tài)化實(shí)例詳解
- Java實(shí)現(xiàn)用Freemarker完美導(dǎo)出word文檔(帶圖片)
- 基于Freemarker和xml實(shí)現(xiàn)Java導(dǎo)出word
- JAVA集成Freemarker生成靜態(tài)html過(guò)程解析
- Java超級(jí)實(shí)用的Freemarker工具類
- 在Java中FreeMarker?模板來(lái)定義字符串模板
- Java使用Freemarker頁(yè)面靜態(tài)化生成的實(shí)現(xiàn)
相關(guān)文章
Android懸浮窗按鈕實(shí)現(xiàn)點(diǎn)擊并顯示/隱藏多功能列表
這篇文章主要為大家詳細(xì)介紹了Android懸浮窗按鈕實(shí)現(xiàn)點(diǎn)擊并顯示/隱藏多功能列表,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-07-07Android 錄音與播放功能的簡(jiǎn)單實(shí)例
這篇文章主要介紹了 Android 錄音與播放功能的簡(jiǎn)單實(shí)例的相關(guān)資料,需要的朋友可以參考下2017-06-06Android 利用方向傳感器實(shí)現(xiàn)指南針具體步驟
Android利用方向傳感器實(shí)現(xiàn)指南針功能,聽(tīng)起來(lái)還不錯(cuò)吧,下面與大家分享下具體的實(shí)現(xiàn)步驟,感興趣的朋友可以參考下哈2013-06-06Android屬性動(dòng)畫(huà)實(shí)現(xiàn)炫酷的登錄界面
這篇文章主要為大家詳細(xì)介紹了Android屬性動(dòng)畫(huà)實(shí)現(xiàn)炫酷的登錄界面,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-07-07Android應(yīng)用啟動(dòng)速度優(yōu)化
這篇文章主要介紹了Android應(yīng)用啟動(dòng)速度優(yōu)化的相關(guān)資料,需要的朋友可以參考下2016-01-01Android 圖文詳解Binder進(jìn)程通信底層原理
Android系統(tǒng)中,多進(jìn)程間的通信都是依賴于底層Binder IPC機(jī)制,Binder機(jī)制是一種RPC方案。例如:當(dāng)進(jìn)程A中的Activity與進(jìn)程B中的Service通信時(shí),就使用了binder機(jī)制2021-10-10Android Tween動(dòng)畫(huà)之RotateAnimation實(shí)現(xiàn)圖片不停旋轉(zhuǎn)效果實(shí)例介紹
Android中如何使用rotate實(shí)現(xiàn)圖片不停旋轉(zhuǎn)的效果,下面與大家共同分析下Tween動(dòng)畫(huà)的rotate實(shí)現(xiàn)旋轉(zhuǎn)效果,感興趣的朋友可以參考下哈2013-05-05