首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 开源软件 >

Velocity模板发动机入门

2012-11-09 
Velocity模板引擎入门类似于PHP中的Smarty,Velocity是一个基于java的模板引擎(template engine)。它允许任

Velocity模板引擎入门

类似于PHP中的Smarty,Velocity是一个基于java的模板引擎(template engine)。它允许任何人仅仅简单的使用模板语言(template language)来引用由java代码定义的对象。从而实现界面和Java代码的分离,使得界面设计人员可以和java程序开发人员同步开发一个遵循MVC架构的web站点。

另外,Velocity的能力远不止web站点开发这个领域,例如,它可以从模板(template)产生SQL和PostScript、XML,它也可以被当作一个独立工具来产生源代码和报告,或者作为其他系统的集成组件使用。Velocity也可以为Turbine web开发架构提供模板服务(template service)。Velocity+Turbine提供一个模板服务的方式允许一个web应用以一个真正的MVC模型进行开发。


编写Velocity版的Hello World
获取Velocity相关JAR文件:

从http://velocity.apache.org/网站上下载最新的Velocity,这里我们下载了velocity-1.7.zip

相关Jar包添加到项目中:

解压velocity-1.7.zip,发下其根目录下有两个JAR文件:

velocity-1.7.jar velocity-1.7-dep.jar

其中velocity-1.7-dep.jar包含了:

velocity-1.7.jar commons-collections-3.2.1.jar commons-lang-2.4.jar oro-2.0.8.jar(这些JAR文件位于解压目录的lib目录下)

在JAR包不冲突的情况下可以直接使用velocity-1.7-dep.jar

载类路径下添加velocity.properties文件:

该文件一般包含如下配置:

?

//初始化模板引擎Velocity.init("src/velocity.properties");//获取VelocityContextVelocityContext context = new VelocityContext();//为Context设置变量context.put("content", "HelloWorld");context.put("who", "arthinking");//获取模板文件Template template = Velocity.getTemplate("helloworld.vm");//创建输出文件File output = new File("D:/Velocity/1.html");if(!output.getParentFile().exists())output.getParentFile().mkdir();//创建输出流FileOutputStream outputStream = new FileOutputStream(output);OutputStreamWriter writer = new OutputStreamWriter(outputStream);BufferedWriter bufferedWriter = new BufferedWriter(writer);template.merge(context, bufferedWriter);bufferedWriter.flush();outputStream.close();bufferedWriter.close();

?

?

转自:http://www.itzhai.com/the-introduction-of-the-velocity-template-engine-template-language-syntax-and-basic-use.html

热点排行