您的位置:首页 > 编程语言 > Java开发

Java项目Freemark生成静态页面及语法

2015-07-14 16:43 686 查看
做门户网站有大量的页面 页面数据之多 每次请求都要查询数据库操作 性能 差 速度也慢的不得了 使用freemark生成静态页面

FreeMarker 是一个用Java编写的模板引擎,主要用来生成HTML Web页面,特别是基于MVC模式的应用程序。虽然FreeMarker具有一些编程的能力,但不像PHP,通常由Java程序准备要显示的数据,由 FreeMarker模板生成页面。 FreeMarker可以作为Web应用框架一个组件,但它与容器无关,在非Web应用程序环境也能工作的很好。 FreeMarker适合作为MVC的视图组件,还能在模板中使用JSP标记库。

ftl模板 + Map数据模型 = 输出html

首先编写使ftl模板可以生成html的代码 必需导入freemark包

Java代码





public class CreateHTML {
private Configuration freemarker_cfg = null;

// private String sGeneFilePath = null;
// private String sGeneFileName = null;
// private String sTempPlateFilePath = null;

/**
* 创建多级目录
*
* @param path
* String
* @return boolean 是否成功
*/
private boolean creatDirs(String path) {
File aFile = new File(path);
if (!aFile.exists()) {
return aFile.mkdirs();
} else {
return true;
}
}

/**
* 生成静态文件.
*
* @param templateFileName
* 模板文件名,相对htmlskin路径,例如"/tpxw/view.ftl"
* @param propMap
* 用于处理模板的属性Object映射
* @param htmlFilePath
* 要生成的静态文件的路径,相对设置中的根路径,例如 "/tpxw/1/2005/4/"
* @param htmlFileName
* 要生成的文件名,例如 "1.htm"
* @param templateFilePath
* 模板路径
* @return boolean true代表生成文件成功
*/
@SuppressWarnings("unchecked")
public void geneHtmlFile(String templateFileName, Map propMap,
String htmlFilePath, String htmlFileName, String templateFilePath) {

try {
Template t = this.getFreeMarkerCFG(templateFilePath).getTemplate(
templateFileName);
// 如果根路径存在,则递归创建子目录
this.creatDirs(htmlFilePath);
File afile = new File(htmlFilePath + "/" + htmlFileName);
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(afile)));
t.process(propMap, out);
out.flush();
out.close();
} catch (TemplateException e) {
System.out.print(e.getMessage());
} catch (IOException e) {
System.out.print(e.getMessage());
} catch (Exception e) {
System.out.print(e.getMessage());
}
}

/**
*
* 获取freemarker的配置. freemarker本身支持classpath,目录和从ServletContext获取.
*
* @param templateFilePath
* 获取模板路径
* @return Configuration 返回freemaker的配置属性
* @throws Exception
*/
private Configuration getFreeMarkerCFG(String templateFilePath)
throws Exception {
if (null == this.freemarker_cfg) {

this.freemarker_cfg = new Configuration();
try {
this.freemarker_cfg.setDirectoryForTemplateLoading(new File(
templateFilePath));
} catch (Exception ex) {
throw ex;
}
}
return this.freemarker_cfg;
}

}

写一个定时器 定时生成静态页面

Java代码





public class ContextListener implements ServletContextListener {

private static final long serialVersionUID = 1L;
private Timer timer = null;

public void contextDestroyed(ServletContextEvent event) {
timer.cancel();
event.getServletContext().log("定时器销毁");
}

public void contextInitialized(ServletContextEvent event) {
timer = new Timer(true);
event.getServletContext().log("定时器已启动");
// 6000 参数单位为毫秒 自动调用IndexTask类中的run方法
timer.schedule(new IndexTask(event), 0, 6000);
}
}

调用定时器中的程序 查询数据生成静态页面

Java代码





public class IndexTask extends TimerTask {
ServletContextEvent context;
WebApplicationContext wac;
BlogService blogService;
public IndexTask(ServletContextEvent event) {
context = event;
ServletContext application = context.getServletContext();
wac = WebApplicationContextUtils.getWebApplicationContext(application);

}

public void run() {
try {
//这里使用spring框架
blogService = (BlogService) wac.getBean("blogService");
Map root = new HashMap();
// 會員積分排行 查询数据存放在root Map中 ftl模板可以使用userAlbum
//blogService.findByAlbum是写好的dao查询方法
root.put("userAlbum", blogService.findByAlbum(
"queryTopUserByscore"));
CreateHTML chtml = new CreateHTML();
chtml.geneHtmlFile("index.ftl", root, context.getServletContext()
.getRealPath("/"), "index.html", context
.getServletContext().getRealPath(
"/WEB-INF/templates"));
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}

然后写ftl模板 我把ftl存放在/WEB-INF/templates/ 目录下 新建index.ftl 写要迭代的数据 比如我这里存放的数据名称为userAlbum

Java代码





<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<div id="Layer4_right" class="left">
<div id="Layer4_right_bg1">
<span>个人·博客</span>
<a href="/album/searchAlbum.action>更多>></a>
</div>
<div id="Layer4_right_content">
这里使用#list 迭代数据和foreach差不多 使用了#if #else判断数据的长度
<div id="Layer4_right_content_Gray">
<ul>
<#list userAlbum as pro>
<li>
<a href="/album/searchAlbumDesc.action?shnAlbum.albumid=${pro.albumid!}">
<img src="/upload/photo/smallimage/${pro.images!}" alt="相片"
width="102" height="101" />
</a>
<span>专辑:<a href="/album/searchAlbum.action?albumid=${pro.albumid!}">
<#if (pro.title?length gt 5)>${pro.title[0..3]!}..<#else>${pro.title!}</#if>

</a>
</li>
</#list>
</ul>
</div>
</div>

先来解释一下freemaker的基本语法了,

<# ... > 中存放所有freemaker的内容,之外的内容全部原样输出。

<@ ... /> 是函数调用

两个定界符内的内容中,第一个符号表示指令或者函数名,其后的跟随参数。freemaker提供的控制包括如下:

<#if condition><#elseif condition><#else> 条件判断

<#list hash_or_seq as var> 遍历hash表或者collection(freemaker称作sequence)的成员

<#macro name param1 param2 ... ><#nested param> 宏,无返回参数

<#function name param1 param2><#return val> 函数,有返回参数

var?member_function(...) 用函数对var进行转换,freemaker称为build-ins。实际内部实现类似member_function(var, ...)

stringA[M .. N] 取子字符串,类似substring(stringA, M, N)

{key:value, key2:value2 ...} 直接定义一个hash表

[item0, item1, item2 ...] 直接定义一个序列

hash0[key0] 存取hash表中key对应的元素

seq0[5] 存取序列指定下标的元素

<@function1 param0 param1 ... /> 调用函数function1

<@macro0 param0 param1 ; nest_param0 nest_param1 ...> nest_body < >调用宏,并处理宏的嵌套

<#assign var = value > 定义变量并初始化

<#local var = value> 在 macro 或者 function 中定义局部变量并初始化

<#global var = value > 定义全局变量并初始化

${var} 输出并替换为表达式的值

<#visit xmlnode> 调用macro匹配xmlnode本身及其子节点

<#recurse xmlnode> 调用macro匹配xmlnode的子节点

<#include "index.ftl" encoding="GBK"> 包含另外一个ftl模板标签

eclipse 安装Freemark插件 支持语法加亮 加亮的ftl模板 如下图



我的eclipse版本是galileo
打开菜单项 Help -> install new software... .

点击 Add Update Site... , 输入 " FreeMarker " 作为名字以及 "- http://download.jboss.org/jbosstools/updates/stable/galileo/ 作为更新的地址
选中复选框 "FreeMarker"
点击下一步或完成按钮根据提示完成插件的安装

安装完毕后该插件自动关联*.ftl文件,你也可以在对话框中进行自行设置。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: