Java操作FreeMarker模板引擎的基本用法示例小结
FreeMarker是一个采用Java开发的模版引擎,是一个基于模版生成文本的通用工具。它被设计用来生成HTMLWeb页面,特别是基于MVC模式的应用程序。虽然使用FreeMarker需要具有一些编程的能力,但通常由Java程序准备要显示的数据,由FreeMarker生成页面,并通过模板显示准备的数据。
http://freemarker.org/
publicvoidprocess(Stringtemplate,Map<String,?>data)throwsException{
Configurationcfg=newConfiguration();
cfg.setDirectoryForTemplateLoading(newFile("ftl"));
cfg.setObjectWrapper(newDefaultObjectWrapper());
//设置字符集
cfg.setDefaultEncoding("UTF-8");
//设置尖括号语法和方括号语法,默认是自动检测语法
//自动AUTO_DETECT_TAG_SYNTAX
//尖括号ANGLE_BRACKET_TAG_SYNTAX
//方括号SQUARE_BRACKET_TAG_SYNTAX
cfg.setTagSyntax(Configuration.AUTO_DETECT_TAG_SYNTAX);
Writerout=newOutputStreamWriter(newFileOutputStream(FILE_DIR+template+".txt"),"UTF-8");
Templatetemp=cfg.getTemplate(template);
temp.process(data,out);
out.flush();
}
0、使用freemarker制作HelloWordweb页面
新建一个WEB工程,并导入freemarker.jar,在WEB-INF下新建文件夹templates用于存放模版文件,在templates下新建test.ftl,这是示例模版文件。内容就是HTML内容,里面带有一个标记符,用于将来进行变量替换,内容如下:
<html>
<head>
<title>freemarker测试</title>
</head>
<body>
<h1>${message},${name}</h1>
</body>
</html>
新建一个Servlet,用于请求设置变量,并处理模版的输出:
packagecom.test.servlet;
importjava.io.IOException;
importjava.io.Writer;
importjava.util.HashMap;
importjava.util.Map;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importfreemarker.template.Configuration;
importfreemarker.template.Template;
importfreemarker.template.TemplateException;
@SuppressWarnings("serial")
publicclassHelloFreeMarkerServletextendsHttpServlet{
//负责管理FreeMarker模板的Configuration实例
privateConfigurationcfg=null;
publicvoidinit()throwsServletException{
//创建一个FreeMarker实例
cfg=newConfiguration();
//指定FreeMarker模板文件的位置
cfg.setServletContextForTemplateLoading(getServletContext(),
"/WEB-INF/templates");
}
@SuppressWarnings("unchecked")
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
//建立数据模型
Maproot=newHashMap();
root.put("message","helloworld");
root.put("name","java小强");
//获取模板文件
Templatet=cfg.getTemplate("test.ftl");
//使用模板文件的Charset作为本页面的charset
//使用text/htmlMIME-type
response.setContentType("text/html;charset="+t.getEncoding());
Writerout=response.getWriter();
//合并数据模型和模板,并将结果输出到out中
try{
t.process(root,out);//往模板里写数据
}catch(TemplateExceptione){
e.printStackTrace();
}
}
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
doPost(request,response);
}
publicvoiddestroy(){
super.destroy();
}
}
注意要在你的web.xml中配置该Servlet:
<?xmlversion="1.0"encoding="UTF-8"?> <web-appversion="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做一个简单修改:
<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%> <% Stringpath=request.getContextPath(); StringbasePath=request.getScheme()+"://"+request.getServerName() +":"+request.getServerPort()+path+"/"; %> <html> <body> <% Stringmypath="hello"; response.sendRedirect(basePath+mypath); %> </body> </html>
部署工程到Tomcat,启动并访问http://localhost:8080/f,这里我建立的工程名称就是f。
1、计算式
<#--1、算术运算-->[BR]
${3+4}
<#--2、内建函数-->[BR]
${"rensanning"?upper_case}
2、输出一个值
HashMapt2root=newHashMap<String,String>();
t2root.put("user","RenSanNing");
${user},Welcome!
3、输出一个列表
Map<String,Object>t3root=newHashMap<String,Object>();
List<Food>menu=newArrayList<Food>();
menu.add(newFood("iTextinAction",98));
menu.add(newFood("iBATISinAction",118));
menu.add(newFood("LuceneinAction",69));
t3root.put("menu",menu);
<#listmenuasfood>
${food.name}${food.price?string.currency}
</#list>
4、逻辑判断(IF,SWITCH)
Map<String,Object>t4root=newHashMap<String,Object>();
t4root.put("x",2);
t4root.put("y","medium");
<1>if,else,elseif:
<#ifx==1>
xis1
<#elseifx==2>
xis2
<#elseifx==3>
xis3
<#elseifx==4>
xis4
<#else>
xisnot1nor2nor3nor4
</#if>
<2>switch,case,default,break:
<#switchy>
<#case"small">
Thiswillbeprocessedifitissmall
<#break>
<#case"medium">
Thiswillbeprocessedifitismedium
<#break>
<#case"large">
Thiswillbeprocessedifitislarge
<#break>
<#default>
Thiswillbeprocessedifitisneither
</#switch>
<3>list,break:
<#assignseq=["winter","spring","summer","autumn"]>
<#listseqasx>
${x_index+1}.${x}<#ifx_has_next>,</#if>
</#list>
5、自定义函数
<#functionfactn>
<#ifn==0>
<#return1/>
<#else>
<#returnfact(n-1)*n/>
</#if>
</#function>
<#list0..10asi>
${i}!=>${fact(i)}
</#list>
6、定义变量
<#--1、本地变量-->[BR]
<#functionpartgnlst>
<#localans=[]>
<#listlstasx>
<#if(x>=n)>
<#localans=ans+[x]>
</#if>
</#list>
<#returnans>
</#function>
<#assignls=[10,2,4,5,8,1,3]>
<#listpartg(4,ls)asx>${x}</#list>
<#--2、变量域测试-->[BR]
<#macrotest>
03.${x}
<#globalx="global2">
04.${x}
<#assignx="assign2">
05.${x}
<#localx="local1">
06.${x}
<#list["循环1"]asx>
07.${x}
<#localx="local2">
08.${x}
<#assignx="assign3">
09.${x}
</#list>
10.${x}
</#macro>
<#globalx="global1"/>
01.${x}
<#assignx="assign1"/>
02.${x}
<@test/>
11.${x}
7、定义宏macro
<#--1、无参数-->[BR]
<#macrogreet>
Welcome!
</#macro>
<@greet/>
<#--2、有参数-->[BR]
<#macrogreetuser>
${user},Welcome!
</#macro>
<@greetuser="RenSanNing"/>
<#--3、有多个参数-->[BR]
<#macrotablecolsrows>
<table>
<#list1..rowsasrow>
<tr>
<#list1..colsascol>
<td>${row},${col}</td>
</#list>
</tr>
</#list>
</table>
</#macro>
<@tablecols=3rows=2/>
<#--4、中间跳出-->[BR]
<#macroout>
显示文字
<#return>
不显示文字
</#macro>
<@out/>
<#--5、嵌套-->[BR]
<#macrolprintlst>
<#listlstasitem>
・${item}<#nesteditem/>
</#list>
</#macro>
<@lprint1..3;x>^2=${x*x}</@lprint>
<@lprint1..3;x>^3=${x*x*x}</@lprint>
<@lprint["Let'sgo","tothe","landofMedetai"]/>
8、include
<#include"T108include.ftl">
${url}
<@greetname="rensanning"/>
T108include.ftl
<#macrogreetname>
${name},Welcome!
</#macro>
<#assignurl="http://www.baidu.com/">
9、名字空间
<#import"T109include.ftl"asmy>
<#assignurl="http://www.google.com/">
${my.url}
<@my.greetname="rensanning"/>
${url}
T109include.ftl
<#macrogreetname>
${name},Welcome!
</#macro>
<#assignurl="http://www.baidu.com/">
10、自定义指令Directive
publicclassSystemDateDirectiveimplementsTemplateDirectiveModel{
publicvoidexecute(Environmentenv,Mapparams,TemplateModel[]loopVars,
TemplateDirectiveBodybody)throwsTemplateException,IOException{
Calendarcal=Calendar.getInstance();
SimpleDateFormatsdf=newSimpleDateFormat("yyyy/MM/ddHH:mm:ss");
env.getOut().append(sdf.format(cal.getTime()));
}
}
publicclassTextCutDirectiveimplementsTemplateDirectiveModel{
publicstaticfinalStringPARAM_S="s";
publicstaticfinalStringPARAM_LEN="len";
publicstaticfinalStringPARAM_APPEND="append";
@SuppressWarnings("unchecked")
publicvoidexecute(Environmentenv,Mapparams,TemplateModel[]loopVars,
TemplateDirectiveBodybody)throwsTemplateException,IOException{
Strings=getString(PARAM_S,params);
Integerlen=getInt(PARAM_LEN,params);
Stringappend=getString(PARAM_APPEND,params);
if(s!=null){
Writerout=env.getOut();
if(len!=null){
out.append(textCut(s,len,append));
}else{
out.append(s);
}
}
}
....
Map<String,Object>t10root=newHashMap<String,Object>();
t10root.put("systemdate",newSystemDateDirective());
t10root.put("text_cut",newTextCutDirective());