欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2024-02-26 09:44:13
freemarker 是一个采用 java 开发的模版引擎,是一个基于模版生成文本的通用工具。 它被设计用来生成 html web 页面,特别是基于 mvc 模式的应用程序...

freemarker 是一个采用 java 开发的模版引擎,是一个基于模版生成文本的通用工具。 它被设计用来生成 html web 页面,特别是基于 mvc 模式的应用程序。虽然使用freemarker需要具有一些编程的能力,但通常由 java 程序准备要显示的数据,由 freemarker 生成页面,并通过模板显示准备的数据。
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()); 
   
  //设置字符集 
  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内容,里面带有一个标记符,用于将来进行变量替换,内容如下:

<html> 
 <head> 
    <title>freemarker测试</title> 
  </head> 
  <body> 
    <h1>${message},${name}</h1> 
  </body> 
</html> 

 
新建一个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:

<?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> 

 
为了方便测试,访问工程直接跳转到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+"/"; 
%> 
<html> 
 <body> 
  <% 
  string mypath = "hello"; 
  response.sendredirect(basepath + mypath); 
  %> 
 </body> 
</html> 

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

1、计算式

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

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


2、输出一个值

hashmap t2root = new hashmap<string, string>(); 
t2root.put("user", "rensanning"); 

${user}, welcome!


3、输出一个列表

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、自定义函数

<#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、变量域测试 -->[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} 
  </#list> 
  10. ${x} 
</#macro> 

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


7、定义宏macro

<#-- 1、无参数 -->[br] 
<#macro greet> 
welcome! 
</#macro> 

<@greet /> 

<#-- 2、有参数 -->[br] 
<#macro greet user> 
${user}, welcome! 
</#macro> 

<@greet user="rensanning"/> 

<#-- 3、有多个参数 -->[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());