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

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

 

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

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

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

Java代码   收藏代码
  1. public class CreateHTML {  
  2.     private Configuration freemarker_cfg = null;  
  3.   
  4.     // private String sGeneFilePath = null;  
  5.     // private String sGeneFileName = null;  
  6.     // private String sTempPlateFilePath = null;  
  7.   
  8.     /** 
  9.      * 创建多级目录 
  10.      *  
  11.      * @param path 
  12.      *            String 
  13.      * @return boolean 是否成功 
  14.      */  
  15.     private boolean creatDirs(String path) {  
  16.         File aFile = new File(path);  
  17.         if (!aFile.exists()) {  
  18.             return aFile.mkdirs();  
  19.         } else {  
  20.             return true;  
  21.         }  
  22.     }  
  23.   
  24.     /** 
  25.      * 生成静态文件. 
  26.      *  
  27.      * @param templateFileName 
  28.      *            模板文件名,相对htmlskin路径,例如"/tpxw/view.ftl" 
  29.      * @param propMap 
  30.      *            用于处理模板的属性Object映射 
  31.      * @param htmlFilePath 
  32.      *            要生成的静态文件的路径,相对设置中的根路径,例如 "/tpxw/1/2005/4/" 
  33.      * @param htmlFileName 
  34.      *            要生成的文件名,例如 "1.htm" 
  35.      * @param templateFilePath 
  36.      *            模板路径 
  37.      * @return boolean true代表生成文件成功 
  38.      */  
  39.     @SuppressWarnings("unchecked")  
  40.     public void geneHtmlFile(String templateFileName, Map propMap,  
  41.             String htmlFilePath, String htmlFileName, String templateFilePath) {  
  42.   
  43.         try {  
  44.             Template t = this.getFreeMarkerCFG(templateFilePath).getTemplate(  
  45.                     templateFileName);  
  46.             // 如果根路径存在,则递归创建子目录  
  47.             this.creatDirs(htmlFilePath);  
  48.             File afile = new File(htmlFilePath + "/" + htmlFileName);  
  49.             Writer out = new BufferedWriter(new OutputStreamWriter(  
  50.                     new FileOutputStream(afile)));  
  51.             t.process(propMap, out);  
  52.             out.flush();  
  53.             out.close();  
  54.         } catch (TemplateException e) {  
  55.             System.out.print(e.getMessage());  
  56.         } catch (IOException e) {  
  57.             System.out.print(e.getMessage());  
  58.         } catch (Exception e) {  
  59.             System.out.print(e.getMessage());  
  60.         }  
  61.     }  
  62.   
  63.     /** 
  64.      *  
  65.      * 获取freemarker的配置. freemarker本身支持classpath,目录和从ServletContext获取. 
  66.      *  
  67.      * @param templateFilePath 
  68.      *            获取模板路径 
  69.      * @return Configuration 返回freemaker的配置属性 
  70.      * @throws Exception 
  71.      */  
  72.     private Configuration getFreeMarkerCFG(String templateFilePath)  
  73.             throws Exception {  
  74.         if (null == this.freemarker_cfg) {  
  75.   
  76.             this.freemarker_cfg = new Configuration();  
  77.             try {  
  78.                 this.freemarker_cfg.setDirectoryForTemplateLoading(new File(  
  79.                         templateFilePath));  
  80.             } catch (Exception ex) {  
  81.                 throw ex;  
  82.             }  
  83.         }  
  84.         return this.freemarker_cfg;  
  85.     }  
  86.   
  87. }  

 

 

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

 

Java代码   收藏代码
  1. public class ContextListener implements ServletContextListener {  
  2.   
  3.     private static final long serialVersionUID = 1L;  
  4.     private Timer timer = null;  
  5.   
  6.     public void contextDestroyed(ServletContextEvent event) {  
  7.         timer.cancel();  
  8.         event.getServletContext().log("定时器销毁");  
  9.     }  
  10.   
  11.     public void contextInitialized(ServletContextEvent event) {  
  12.         timer = new Timer(true);  
  13.         event.getServletContext().log("定时器已启动");  
  14.         // 6000  参数单位为毫秒  自动调用IndexTask类中的run方法  
  15.         timer.schedule(new IndexTask(event), 06000);  
  16.     }  
  17. }  
 

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

Java代码   收藏代码
  1. public class IndexTask extends TimerTask {  
  2.        ServletContextEvent context;  
  3.     WebApplicationContext wac;  
  4.        BlogService blogService;  
  5.     public IndexTask(ServletContextEvent event) {  
  6.         context = event;  
  7.         ServletContext application = context.getServletContext();  
  8.         wac = WebApplicationContextUtils.getWebApplicationContext(application);  
  9.   
  10.     }  
  11.   
  12. public void run() {  
  13.         try {  
  14.               //这里使用spring框架  
  15.               blogService = (BlogService) wac.getBean("blogService");  
  16.                       Map root = new HashMap();  
  17.           // 會員積分排行  查询数据存放在root Map中 ftl模板可以使用userAlbum  
  18.          //blogService.findByAlbum是写好的dao查询方法  
  19.               root.put("userAlbum", blogService.findByAlbum(  
  20.                     "queryTopUserByscore"));  
  21.                     CreateHTML chtml = new CreateHTML();  
  22.             chtml.geneHtmlFile("index.ftl", root, context.getServletContext()  
  23.                     .getRealPath("/"), "index.html", context  
  24.                     .getServletContext().getRealPath(  
  25.                             "/WEB-INF/templates"));  
  26.     } catch (Exception e) {  
  27.             e.printStackTrace();  
  28.         } finally {  
  29.         }  
  30.     }  
 

 

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

 

Java代码   收藏代码
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   
  2. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4.  <div id="Layer4_right" class="left">  
  5.             <div id="Layer4_right_bg1">  
  6.                 <span>个人·博客</span>  
  7.                 <a href="/album/searchAlbum.action>更多>></a>  
  8.             </div>  
  9.             <div id="Layer4_right_content">  
  10.       这里使用#list  迭代数据和foreach差不多    使用了#if  #else判断数据的长度        
  11.               <div id="Layer4_right_content_Gray">  
  12.                     <ul>  
  13.                         <#list userAlbum as pro>  
  14.             <li>  
  15.            <a href="/album/searchAlbumDesc.action?shnAlbum.albumid=${pro.albumid!}">  
  16.              <img src="/upload/photo/smallimage/${pro.images!}" alt="相片"  
  17.                      width="102" height="101" />  
  18.             </a>  
  19.         <span>专辑:<a href="/album/searchAlbum.action?albumid=${pro.albumid!}">  
  20.              <#if (pro.title?length gt 5)>${pro.title[0..3]!}..<#else>${pro.title!}</#if>  
  21.             </a>  
  22.                   </li>  
  23.         </#list>  
  24.                     </ul>  
  25.                 </div>  
  26.             </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... .

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

安装完毕后该插件自动关联*.ftl文件,你也可以在对话框中进行自行设置。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值