Velocity是一个基于java的模板引擎(template engine)。它同意不论什么人只简单的使用模板语言(template language)来引用由java代码定义的对象。

当Velocity应用于web开发时,界面设计人员能够和java程序开发者同步开发一个遵循MVC架构的web网站,也就是说,页面设计人员能够仅仅 关注页面的显示效果,而由java程序开发者关注业务逻辑编码。Velocity将java代码从web页面中分离出来,这样为web网站的长期维护提 供了便利,同一时候也为我们在JSP,PHP和Freemarker之外又提供了一种可选的方案。

大多数开发者只了解上述部分,即Velocity能够作为MVC的V,所以出现了非常多Velocity和SpringMVC,Velocity和Struts集成的设计。但少有人关注,Velocity作为模板引擎的意义,既然是模板引擎,那它就不应该只局限在MVC的领域。

Velocity的能力远不止web网站开发这个领域,比如,它能够从模板(template)产生SQL和PostScript、XML,它也能够被当 作一个独立工具来产生源码和报告,或者作为其它系统的集成组件使用。

下面代码,是我对Velocity的简单封装,能够将Velocity作为单独的组件来使用,稍加丰富就能够成为我们应用的模板引擎。

核心代码:

  1. package com.ths.platform.framework.template;
  2.  
  3. import java.io.BufferedWriter;
  4. import java.io.FileOutputStream;
  5. import java.io.OutputStream;
  6. import java.io.OutputStreamWriter;
  7. import java.util.Properties;
  8. import org.apache.velocity.Template;
  9. import org.apache.velocity.VelocityContext;
  10. import org.apache.velocity.app.Velocity;
  11. import org.apache.velocity.app.VelocityEngine;
  12.  
  13. public class VelocityParser
  14. {
  15. //模板上下文
  16. private VelocityContext mainContext;
  17. //模板对象
  18. private Template mainTemplate;
  19. //模板引擎
  20. private VelocityEngine velocityEngine;
  21. //模板引擎初始化參数
  22. private Properties properties;
  23.  
  24. public static void main( String[ ] args ) {
  25. String filepath = "template/view.jsp";
  26. VelocityParser velocityParser = new VelocityParser( filepath );
  27. velocityParser.addToContext( "title" , "HelloWorld" );
  28. velocityParser.processTemplate( );
  29. }
  30.  
  31. /**
  32. * @MethodName : addToContext
  33. * @Description : 向模板上下文中加入參数
  34. * @param key
  35. * @param value
  36. */
  37. public void addToContext( String key, Object value ) {
  38. if ( mainContext == null )
  39. {
  40. mainContext = new VelocityContext( );
  41. }
  42.  
  43. mainContext.put( key , value );
  44. }
  45.  
  46. /**
  47. * @MethodName : addToContext
  48. * @Description :初始化模板上下文
  49. * @param chainCtx
  50. */
  51. public void addToContext( VelocityContext chainCtx ) {
  52. mainContext = new VelocityContext( chainCtx );
  53. }
  54.  
  55. /**
  56. * @MethodName : processTemplate
  57. * @Description : 输出到控制台
  58. */
  59. public void processTemplate() {
  60. try
  61. {
  62. BufferedWriter writer = new BufferedWriter( new OutputStreamWriter( System.out ) );
  63. if ( mainTemplate != null )
  64. {
  65. mainTemplate.merge( mainContext , writer );
  66. }
  67.  
  68. writer.flush( );
  69. writer.close( );
  70. }
  71. catch ( Exception ex )
  72. {
  73. ex.printStackTrace( );
  74. }
  75. }
  76.  
  77. /**
  78. * @MethodName : processTemplate
  79. * @Description : 输出到文件
  80. * @param destPath
  81. */
  82. public void processTemplate(String destPath) {
  83. try
  84. {
  85. OutputStream os = new FileOutputStream(destPath);
  86. OutputStreamWriter writer = new OutputStreamWriter(os, "UTF-8");
  87.  
  88. if ( mainTemplate != null )
  89. {
  90. mainTemplate.merge( mainContext , writer );
  91. }
  92.  
  93. writer.flush( );
  94. writer.close( );
  95. }
  96. catch ( Exception ex )
  97. {
  98. ex.printStackTrace( );
  99. }
  100. }
  101.  
  102. /**
  103. * 依据模板文件初始化模板引擎
  104. * @param templateFile
  105. */
  106. public VelocityParser( String templateFile ) {
  107.  this(templateFile , null);
  108. }
  109.  
  110. /**
  111. * 依据模板文件和模板上下文(參数)初始化模板引擎
  112. * @param templateFile
  113. * @param chainContext
  114. */
  115. public VelocityParser( String templateFile , VelocityContext chainContext ) {
  116. try
  117. {
  118. //新建模板引擎
  119. velocityEngine = new VelocityEngine( );
  120.  
  121. //获取初始化參数
  122. properties = initProperties( );
  123.  
  124. //初始化模板引擎
  125. velocityEngine.init( properties );
  126.  
  127. //获取模板对象
  128. mainTemplate = velocityEngine.getTemplate( templateFile );
  129.  
  130. //设置模板上下文
  131.   if(chainContext!=null){
  132.                 //设置模板上下文
  133.                 mainContext = chainContext;
  134.             }
  135.  
  136. }
  137. catch ( Exception ex )
  138. {
  139. System.out.println( "Error processing template file: " + templateFile );
  140. }
  141. }
  142.  
  143. /**
  144. * @MethodName : initProperties
  145. * @Description : 设置初始化參数
  146. * @return
  147. */
  148. private Properties initProperties() {
  149. Properties properties = new Properties( );
  150. //设置从classpath中载入模板文件
  151. properties.setProperty( Velocity.FILE_RESOURCE_LOADER_PATH , Thread.currentThread( )
  152. .getContextClassLoader( ).getResource( "" ).getPath( ) );
  153. //解决模板中文乱码
  154. properties.setProperty( Velocity.INPUT_ENCODING , "utf-8" );
  155. properties.setProperty( Velocity.OUTPUT_ENCODING , "utf-8" );
  156. return properties;
  157. }
  158.  
  159. }

模板:
  1. <table>
  2. <tr><td>$title</td></tr>
  3. </table>

运行main方法,就可以在控制台输出模板和參数合并后生成的数据。

有了这段代码,仅仅要开发过程中,再涉及到反复劳动,再涉及到输出什么报告,仅仅要你能抽取出模板,其它工作,就让它滚犊子去吧。


基于Velocity开发自己的模板引擎的更多相关文章

  1. Spring Boot Web开发与thymeleaf模板引擎

    简介: 使用Springboot应用,选中需要的模块, Spring已经默认将场景配置好了,只需在配置文件中少量配置就可以运行起来 自己编写业务代码 自动配置原理 这个场景Springboot帮我们配 ...

  2. Nunjucks:Mozilla 开发的 JavaScript 模板引擎

    Nunjucks 中文网站:https://nunjucks.bootcss.com/

  3. Spring Boot Web开发中Thymeleaf模板引擎的使用

    这里使用的是idea 1.新建Spring Boot项目 File-->New-->Project...,然后选择左边的Spring Initializr-->Next,可根据自己的 ...

  4. php模板引擎

    http://baike.baidu.com/link?url=HmXfdJBv3zpCdnZPeaSmZmqDBHlyTBnz9Rmb5it-jf1_NLHfaku6_i8ssUYbnaTQEBD4 ...

  5. 一些基于jQuery开发的控件

    基于jQuery开发,非常简单的水平方向折叠控件.主页:http://letmehaveblog.blogspot.com/2007/10/haccordion-simple-horizontal-a ...

  6. PHP模板引擎,Smarty定义

    PHP模板引擎:PHP是一种HTML内嵌式的在服务器端执行的脚本语言.初始的开发模板就是混合 层的数据编程,虽然通过MVC的设计模式可以实现将程序的应用逻辑与网页的呈现逻辑强制 分离,但也只是将程序的 ...

  7. jquery的一个模板引擎-zt

    jQuery-jTemplate.js下载:http://jtemplates.tpython.com/ 一 , 简单介绍 它是一个基于jQuery开发的javascript模板引擎.它主要的作用如下 ...

  8. Spring Boot 系列(五)web开发-Thymeleaf、FreeMarker模板引擎

    前面几篇介绍了返回json数据提供良好的RESTful api,下面我们介绍如何把处理完的数据渲染到页面上. Spring Boot 使用模板引擎 Spring Boot 推荐使用Thymeleaf. ...

  9. JS模板引擎:基于字符串拼接

    目的 编写一个基于字符串拼接的js模板引擎雏形,这里并不会提供任何模板与数据的绑定. 基本原理 Javascript中创建函数的方式有多种,包括: 1. var func = function () ...

随机推荐

  1. ZooKeeper安装与运行

    ZooKeeper安装与运行 首先从官网下载ZooKeeper压缩包,然后解压下载得到的ZooKeeper压缩包,发现有“bin,conf,lib”等目录.“bin目录”中存放有运行脚本:“conf目 ...

  2. poj 3304(直线与线段相交)

    传送门:Segments 题意:线段在一个直线上的摄影相交 求求是否存在一条直线,使所有线段到这条直线的投影至少有一个交点 分析:可以在共同投影处作原直线的垂线,则该垂线与所有线段都相交<==& ...

  3. Ubuntu14.04搭建android开发环境

    一 下载ADT 官方下载地址:http://developer.android.com/sdk/index.html(须要FQ或者改动host) 二 解压 1 使用终端将下载的文件解压当前文件夹下: ...

  4. ACM-简单题之Least Common Multiple——hdu1019

    ***************************************转载请注明出处:http://blog.csdn.net/lttree************************** ...

  5. 八.使用OpenCv图像平滑操作

    1.cvSmooth函数 函数 cvSmooth 可使用简单模糊.简单无缩放变换的模糊.中值模糊.高斯模糊.双边滤波的不论什么一种方法平滑图像.每一种方法都有自己的特点以及局限. 没有缩放的图像平滑仅 ...

  6. 【ASP.NET】怎样使用类创建公共函数,在不同ASP.NET页面间反复调用

    为了降低代码冗余,应将公共函数写在类中,供不同ASP.NET页面调用. 1,先新建一个类,并在类中加入函数逻辑 namespace public_function_demo { public clas ...

  7. UVA 11324 - The Largest Clique(强连通分量+缩点)

    UVA 11324 - The Largest Clique 题目链接 题意:给定一个有向图,要求找一个集合,使得集合内随意两点(u, v)要么u能到v,要么v能到u,问最大能选几个点 思路:强连通分 ...

  8. 安装pygame

    pygame的安装 我们首先要去到:http://www.pygame.org/download.shtml 下载我们所需要的软件包: 我选择的是:pygame-1.9.2a0.win32-py3.2 ...

  9. Python学习入门基础教程(learning Python)--3.2 if-else分支语句

    if-else分支语句结构的特点是当conditon条件满足时,执行if下的语句块,当condition条件不满足时执行else下的语句块,也就是说根据条件来控制让某些语句执行,某些语句不被执行. i ...

  10. Javascript语言精粹之String常用方法分析

    Javascript语言精粹之String常用方法分析 1. String常用方法分析 1.1 String.prototype.slice() slice(start,end)方法复制string的 ...