一、概述
freemarker 是一个模板引擎,一个基于模板生成文本输出的通用工具,使用纯 java 编写,freemarker 被设计用来生成 html web 页面,特别是基于 mvc 模式的应用程序,虽然 freemarker 具有一些编程的能力,但通常由 java 程序准备要显示的数据,由freemarker 生成页面,通过模板显示准备的数据(如下图)
freemarker 不是一个 web 应用框架,而适合作为 web 应用框架一个组件。freemarker 与容器无关,因为它并不知道 http 或 servlet;freemarker 同样可以应用于非web应用程序环境,freemarker 更适合作为 model2 框架(如 struts)的视图组件,你也可以在模板中使用 jsp标记库。另外,freemarker是免费的。
二、freemarker的准备条件
freemarker.2.3.16.jar,下载地址这里就不贴了..(这个jar包其实在struts2里面)
三、freemarker生成静态页面的原理
freemarker 生成静态页面,首先需要使用自己定义的模板页面,这个模板页面可以是最最普通的html,也可以是嵌套freemarker中的 取值表达式, 标签或者自定义标签等等,然后后台读取这个模板页面,解析其中的标签完成相对应的操作, 然后采用键值对的方式传递参数替换模板中的的取值表达式,做完之后 根据配置的路径生成一个新的html页面, 以达到静态化访问的目的。
四、freemarker提供的标签
freemarker提供了很多有用 常用的标签,freemarker标签都是885fdb74da354267290f864b346f7f4c这样子命名的,${value} 表示输出变量名的内容 ,具体如下:
1、list:该标签主要是进行迭代服务器端传递过来的list集合,比如:
<#list namelist as names>
${names}
</#list>
name是list循环的时候取的一个循环变量,freemarker在解析list标签的时候,等价于:
for (string names : namelist) {
system.out.println(names);
}
2、if:该标签主要是做if判断用的,比如:
<#if (names=="陈靖仇")>
他的武器是: 十五~~
</#if>
这个是条件判断标签,要注意的是条件等式必须用括号括起来, 等价于:
if(names.equals("陈靖仇")){
system.out.println("他的武器是: 十五~~");
}
3、include:该标签用于导入文件用的。
<#include "include.html"/>
这个导入标签非常好用,特别是页面的重用。
另外在静态文件中可以使用${} 获取值,取值方式和el表达式一样,非常方便。
下面举个例子(static.html):
<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>insert title here</title>
</head>
<body>
描述:${description}
<br/>
集合大小:${namelist?size}
<br/>
迭代list集合:
<br/>
<#list namelist as names>
这是第${names_index+1}个人,叫做:<label style="color:red">${names}</label>
if判断:
<br/>
<#if (names=="陈靖仇")>
他的武器是: 十五~~
<#elseif (names=="宇文拓")> <#--注意这里没有返回而是在最后面-->
他的武器是: 轩辕剑~·
<#else>
她的绝招是:蛊毒~~
</#if>
<br/>
</#list>
迭代map集合:
<br/>
<#list weaponmap?keys as key>
key--->${key}<br/>
value----->${weaponmap[key]!("null")}
<#--
fremarker 不支持null, 可以用! 来代替为空的值。
其实也可以给一个默认值
value-----${weaponmap[key]?default("null")}
还可以 在输出前判断是否为null
<#if weaponmap[key]></#if>都可以
-->
<br/>
</#list>
include导入文件:
<br/>
<#include "include.html"/>
</body>
</html>
实际代码:
package com.chenghui.test;
import java.io.file;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.outputstreamwriter;
import java.io.writer;
import java.util.arraylist;
import java.util.hashmap;
import java.util.list;
import java.util.map;
import freemarker.template.configuration;
import freemarker.template.defaultobjectwrapper;
import freemarker.template.template;
import freemarker.template.templateexception;
public class createhtml {
public static void main(string[] args) {
try {
//创建一个合适的configration对象
configuration configuration = new configuration();
configuration.setdirectoryfortemplateloading(new file("d:\\project\\webproject\\webcontent\\web-inf\\template"));
configuration.setobjectwrapper(new defaultobjectwrapper());
configuration.setdefaultencoding("utf-8"); //这个一定要设置,不然在生成的页面中 会乱码
//获取或创建一个模版。
template template = configuration.gettemplate("static.html");
map<string, object> parammap = new hashmap<string, object>();
parammap.put("description", "我正在学习使用freemarker生成静态文件!");
list<string> namelist = new arraylist<string>();
namelist.add("陈靖仇");
namelist.add("玉儿");
namelist.add("宇文拓");
parammap.put("namelist", namelist);
map<string, object> weaponmap = new hashmap<string, object>();
weaponmap.put("first", "轩辕剑");
weaponmap.put("second", "崆峒印");
weaponmap.put("third", "女娲石");
weaponmap.put("fourth", "神农鼎");
weaponmap.put("fifth", "伏羲琴");
weaponmap.put("sixth", "昆仑镜");
weaponmap.put("seventh", null);
parammap.put("weaponmap", weaponmap);
writer writer = new outputstreamwriter(new fileoutputstream("success.html"),"utf-8");
template.process(parammap, writer);
system.out.println("恭喜,生成成功~~");
} catch (ioexception e) {
e.printstacktrace();
} catch (templateexception e) {
e.printstacktrace();
}
}
}
这样子基本上可以算的上可以简单的去做一点简单的生成了,但是要在实际中去运用,还是差的很远的,因为freemarker给的标签完全满足不了我们的需要,这时候就需要自定义标签来完成我们的需求了。。
五、freemarker自定义标签
freemarker自定义标签就是自己写标签,然后自己解析,完全由自己来控制标签的输入输出,极大的为程序员提供了很大的发挥空间。
基于步骤:
以前写标签需要在<后加# ,但是freemarker要识别自定义标签需要在后面加上@,然后后面可以定义一些参数,当程序执行template.process(parammap, out);,就会去解析整个页面的所有的freemarker标签。
自定义标签 需要自定义一个类,然后实现templatedirectivemodel,重写execute方法,完成获取参数,根据参数do something等等。。
将自定义标签与解析类绑定在一起需要在parammap中放入该解析类的实例,存放的key与自定义标签一致即可。。
注意:在自定义标签中,如果标签内什么也没有,开始标签和结束标签绝对不能再同一行,不然会报错
freemarker.log.jdk14loggerfactory$jdk14logger error
我曾经上当过,这是freemarker 存在的bug。
下面是static.html的例子:
<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>insert title here</title>
</head>
<body>
<#--自定义变量-->
<#assign num='hehe'/>
${num}
<br/>
自定义标签
<@content name="chenghui" age="120">
${output}
${append}
</@content>
</body>
</html>
下面是上面的static.html模板的解析类:
package com.chenghui.test;
import static freemarker.template.objectwrapper.default_wrapper;
import java.io.ioexception;
import java.io.writer;
import java.util.map;
import freemarker.core.environment;
import freemarker.template.templatedirectivebody;
import freemarker.template.templatedirectivemodel;
import freemarker.template.templateexception;
import freemarker.template.templatemodel;
import freemarker.template.templatemodelexception;
import freemarker.template.templatenumbermodel;
import freemarker.template.templatescalarmodel;
/**
* 自定义标签解析类
* @author administrator
*
*/
public class contentdirective implements templatedirectivemodel{
private static final string param_name = "name";
private static final string param_age = "age";
@override
public void execute(environment env, map params,templatemodel[] loopvars,
templatedirectivebody body) throws templateexception, ioexception {
if(body==null){
throw new templatemodelexception("null body");
}else{
string name = getstring(param_name, params);
integer age = getint(param_age, params);
//接收到参数之后可以根据做具体的操作,然后将数据再在页面中显示出来。
if(name!=null){
env.setvariable("output", default_wrapper.wrap("从contentdirective解析类中获得的参数是:"+name+", "));
}
if(age!=null){
env.setvariable("append", default_wrapper.wrap("年龄:"+age));
}
writer out = env.getout();
out.write("从这里输出可以再页面看到具体的内容,就像document.writer写入操作一样。<br/>");
body.render(out);
/*
如果细心的话,会发现页面上是显示out.write()输出的语句,然后再输出output的内容,
可见 在body在解析的时候会先把参数放入env中,在页面遇到对应的而来表单时的才会去取值
但是,如果该表单时不存在,就会报错, 我觉得这里freemarker没有做好,解析的时候更加会把错误暴露在页面上。
可以这样子弥补${output!"null"},始终感觉没有el表达式那样好。
*/
}
}
/**
* 获取string类型的参数的值
* @param paramname
* @param parammap
* @return
* @throws templatemodelexception
*/
public static string getstring(string paramname, map<string, templatemodel> parammap) throws templatemodelexception{
templatemodel model = parammap.get(paramname);
if(model == null){
return null;
}
if(model instanceof templatescalarmodel){
return ((templatescalarmodel)model).getasstring();
}else if (model instanceof templatenumbermodel) {
return ((templatenumbermodel)model).getasnumber().tostring();
}else{
throw new templatemodelexception(paramname);
}
}
/**
*
* 获得int类型的参数
* @param paramname
* @param parammap
* @return
* @throws templatemodelexception
*/
public static integer getint(string paramname, map<string, templatemodel> parammap) throws templatemodelexception{
templatemodel model = parammap.get(paramname);
if(model==null){
return null;
}
if(model instanceof templatescalarmodel){
string str = ((templatescalarmodel)model).getasstring();
try {
return integer.valueof(str);
} catch (numberformatexception e) {
throw new templatemodelexception(paramname);
}
}else if(model instanceof templatenumbermodel){
return ((templatenumbermodel)model).getasnumber().intvalue();
}else{
throw new templatemodelexception(paramname);
}
}
}
然后再前面的实际代码中加上:
//自定义标签解析
parammap.put("content", new contentdirective());
这样子基本上可以使用,freemarker完成自定义标签了,解决一写简单的业务逻辑, 但是在实际的项目中不可能这样子去做,因为还没有和spring进行集成使用,每次都需要在解析的时候把解析类的实例放进去。。
更多使用java进行freemarker的web模板开发的基础教程。