发布于 2016-05-16 15:29:50 | 711 次阅读 | 评论: 3 | 来源: PHPERZ

1    简介

Velocity是一款基于Java的模板引擎。它允许Web页面设计者引用Java代码中定义的方法。Web设计者能与根据Model-View-Controller (MVC)模型开发Web网站的Java程序员合作,意味着Web页面设计者能将注意力放在创建设计精良的网站,而程序员能将注意力放在编写代码上。Velocity从Web页面中分离Java代码,使Web网站在长时间运行时更可维护性和提供Java Server Pages(JSP)或PHP的替代方案。

Velocity能用于从模板产生Web页面、SQL、PostScript和其它输出。它能用于作为单独的工具类生成源码和报表,或作为其它系统的一个整合组件。Velocity将为Turbine Web应用程序框架提供模板服务。Velocity+Turbine将提供模板服务允许Web应用程序根据真实MVC模型开发。

2    安装

  • JDK(必须)

  • Jakarta Commons Collections(必须)

  • Jakarta Commons Lang(必须)

  • Excaliburex-AvalonLogkit(可选,如果使用默认的基于文件的日志时需要)

  • Jakarta ORO(可选,当使用org.apache.velocity.convert.WebMacro模板转换工具或org.apache.velocity.app.event.implement.Escape Reference ReferenceInsertionEventHandler时使用

3    实践

3.1    基本步骤

  • 初始化Velocity

  • 创建Context对象

  • 添加数据对象到Context

  • 选择模板

  • “合并”模板和数据产生输出

3.2    单例

模板:

${word}

代码:

Velocity.init();

VelocityContext context = new VelocityContext();

context.put( "word", "Hello Velocity!");

// 模板路径默认是当前项目的根目录

Template template = Velocity.getTemplate("src/main/java/com/study/velocity/HelloWord.vm");

StringWriter sw = new StringWriter();

template.merge(context, sw);

System.out.println(sw);

3.3    多例

与单例不同,多例可以在用一个JVM或Web应用程序中维护多组配置。

VelocityEngine ve = new VelocityEngine();

ve.init();

Template t = ve.getTemplate("src/main/java/com/study/velocity/HelloWord.vm");

StringWriter sw = new StringWriter();

VelocityContext context = new VelocityContext();

context.put( "word", "Hello Velocity!");

t.merge(context, sw);

System.out.println(sw);

最新网友评论  共有(3)条评论 发布评论 返回顶部
PHPERZ网友 发布于2017-05-15 09:43:51
现在都用什么
支持(0)  反对(0)  回复
PHPERZ网友 发布于2016-09-23 02:11:44
谁还用这东西,不好用.
  • 2楼  PHPERZ网友 回复于2017-05-15 09:44:14
    现在都用什么?
  • 支持(0)  反对(1)  回复

    Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务