栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > Android

Java操作FreeMarker模板引擎的基本用法示例小结

Android 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java操作FreeMarker模板引擎的基本用法示例小结

FreeMarker 是一个采用 Java 开发的模版引擎,是一个基于模版生成文本的通用工具。 它被设计用来生成 HTML Web 页面,特别是基于 MVC 模式的应用程序。虽然使用FreeMarker需要具有一些编程的能力,但通常由 Java 程序准备要显示的数据,由 FreeMarker 生成页面,并通过模板显示准备的数据。
http://freemarker.org/

public void process(String template, Map data) throws Exception { 
  Configuration cfg = new Configuration(); 
  cfg.setDirectoryForTemplateLoading(new File("ftl")); 
  cfg.setObjectWrapper(new DefaultObjectWrapper()); 
   
  //设置字符集 
  cfg.setDefaultEncoding("UTF-8"); 
   
  //设置尖括号语法和方括号语法,默认是自动检测语法 
  // 自动 AUTO_DETECT_TAG_SYNTAX 
  // 尖括号 ANGLE_BRACKET_TAG_SYNTAX 
  // 方括号 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页面
新建一个WEB工程,并导入freemarker.jar,在WEB-INF下新建文件夹templates用于存放模版文件,在templates下新建test.ftl,这是示例模版文件。内容就是HTML内容,里面带有一个标记符,用于将来进行变量替换,内容如下:

 
  
    freemarker测试 
   
   
    ${message},${name} 
   
 

 
新建一个Servlet,用于请求设置变量,并处理模版的输出:

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 { 
  // 负责管理FreeMarker模板的Configuration实例 
  private Configuration cfg = null; 
  public void init() throws ServletException { 
    // 创建一个FreeMarker实例 
    cfg = new Configuration(); 
    // 指定FreeMarker模板文件的位置 
    cfg.setServletContextForTemplateLoading(getServletContext(), 
 "/WEB-INF/templates"); 
  } 
  @SuppressWarnings("unchecked") 
  public void doPost(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 
    // 建立数据模型 
    Map root = new HashMap(); 
    root.put("message", "hello world"); 
    root.put("name", "java小强"); 
    // 获取模板文件 
    Template t = cfg.getTemplate("test.ftl"); 
    // 使用模板文件的Charset作为本页面的charset 
    // 使用text/html MIME-type 
    response.setContentType("text/html; charset=" + t.getEncoding()); 
    Writer out = response.getWriter(); 
    // 合并数据模型和模板,并将结果输出到out中 
    try { 
      t.process(root, out); // 往模板里写数据 
    } 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:

 
 
   
    hello 
     
      com.test.servlet.HelloFreeMarkerServlet 
     
   
   
    hello 
    /hello 
   
   
    index.jsp 
   
 

 
为了方便测试,访问工程直接跳转到Servlet,对主页index.jsp做一个简单修改:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 
<% 
String path = request.getContextPath(); 
String basePath = request.getScheme()+"://"+request.getServerName() 
+":"+request.getServerPort()+path+"/"; 
%> 
 
  
  <% 
  String mypath = "hello"; 
  response.sendRedirect(basePath + mypath); 
  %> 
  
 

 
部署工程到Tomcat,启动并访问http://localhost:8080/f ,这里我建立的工程名称就是 f 。

1、计算式

<#-- 1、算术运算 -->[BR] 
${3 + 4} 

<#-- 2、内建函数 -->[BR] 
${"rensanning"?upper_case} 


2、输出一个值

HashMap t2root = new HashMap(); 
t2root.put("user", "RenSanNing"); 

${user}, Welcome!


3、输出一个列表

Map t3root = new HashMap(); 
List menu = new ArrayList(); 
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} 
 


4、逻辑判断(IF,SWITCH)

Map t4root = new HashMap(); 
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 
 

<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 
 

<3>list, break: 
<#assign seq = ["winter", "spring", "summer", "autumn"]> 
<#list seq as x> 
 ${x_index + 1}. ${x}<#if x_has_next>, 
 


5、自定义函数

<#function fact n> 
 <#if n == 0> 
  <#return 1 /> 
 <#else> 
  <#return fact(n - 1) * n /> 
  
 

<#list 0..10 as i> 
 ${i}! => ${fact(i)} 
 


6、定义变量

<#-- 1、本地变量 -->[BR] 
<#function partg n lst> 
 <#local ans = []> 
 <#list lst as x> 
  <#if (x >= n)> 
   <#local ans = ans + [x]> 
   
  
 <#return ans> 
 

<#assign ls = [10, 2, 4, 5, 8, 1, 3]> 
<#list partg(4, ls) as x>${x}  

<#-- 2、变量域测试 -->[BR] 
<#macro test> 
  03. ${x} 
  <#global x = "global2"> 
  04. ${x} 
  <#assign x = "assign2"> 
  05. ${x} 
  <#local x = "local1"> 
  06. ${x} 
  <#list ["循环1"] as x> 
    07. ${x} 
    <#local x = "local2"> 
    08. ${x} 
    <#assign x = "assign3"> 
    09. ${x} 
   
  10. ${x} 
 

<#global x = "global1" /> 
01. ${x} 
<#assign x = "assign1" /> 
02. ${x} 
<@test /> 
11. ${x} 


7、定义宏macro

<#-- 1、无参数 -->[BR] 
<#macro greet> 
Welcome! 
 

<@greet /> 

<#-- 2、有参数 -->[BR] 
<#macro greet user> 
${user}, Welcome! 
 

<@greet user="RenSanNing"/> 

<#-- 3、有多个参数 -->[BR] 
<#macro table cols rows> 
  
  <#list 1..rows as row> 
    
    <#list 1..cols as col> 
     
${row}, ${col}
<@table cols=3 rows=2 /> <#-- 4、中间跳出 -->[BR] <#macro out> 显示文字 <#return> 不显示文字 <@out /> <#-- 5、嵌套 -->[BR] <#macro lprint lst> <#list lst as item> ・${item}<#nested item /> <@lprint 1..3; x>^2 = ${x * x} <@lprint 1..3; x>^3 = ${x * x * x} <@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! 
 

<#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! 
 

<#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 t10root = new HashMap(); 
t10root.put("systemdate", new SystemDateDirective()); 
t10root.put("text_cut", new TextCutDirective()); 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/163117.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号