简介
Velocity是一个基于JAVA的模板引擎,使用这个工具你可以很容易地创建和渲染你所要展示的格式化文档。
官网定义:
Velocity is a Java-based template engine, a simple and powerful development tool
that allows you to easily create and render documents that format and present your data.
基本流程
当在一个应用程序或者一个Servlet中用到Velocity时,你通常会执行以下操作:
- 初始化Velocity。比如初始化日至系统、资源管理器、宏系统等等。
- 创建一个上下文对象(context Object)。
- 将数据对象添加到Context中。
- 选择一种模板。
- 将合并的模板、数据输出。
两个例子
应用程序
//目录结构
├─java
│ │─FooBar.java
│
├─resources
│─hellovelocity.vm
//pom.xml
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-tools</artifactId>
<version>2.0</version>
</dependency>
//FooBar.java
public static void main(String[] args) {
try {
// 初始化模板引擎
VelocityEngine ve = new VelocityEngine();
//org.apache.velocity.runtime.RuntimeConstants 从哪里加载vm文件
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
ve.init();
// 获取模板文件
Template t = ve.getTemplate("hellovelocity.vm");
// 设置变量
VelocityContext ctx = new VelocityContext();
ctx.put("name", "Velocity");
List list = new ArrayList();
list.add("1");
list.add("2");
ctx.put("list", list);
// 输出
StringWriter sw = new StringWriter();
t.merge(ctx, sw);
System.out.println(sw.toString());
} catch (ResourceNotFoundException rnfe) {
// couldn't find the template
} catch (ParseErrorException pee) {
// syntax error: problem parsing the template
} catch (MethodInvocationException mie) {
// something invoked in the template
// threw an exception
} catch (Exception e) {
}
}
//hellovelocity.vm
#set($greet = 'hello')
$greet $name
#foreach($i in $list)
$i
#end
output
hello Velocity
1
2
Web程序
//目录结构
├─java
│ └─config
│ └─ VelocityServlet.java
├─resources
│ └─test.vm
└─webapp
└─WEB-INF
└─ velocity.properties
└─web.xml
//web.xml
<web-app>
<display-name>learn velocity</display-name>
<servlet>
<servlet-name>myVelocity</servlet-name>
<servlet-class>config.VelocityServlet</servlet-class>
<!--定义Velocity配置文件velocity.properties的位置,相对于web应用根的路径-->
<init-param>
<param-name>org.apache.velocity.properties</param-name>
<param-value>/WEB-INF/velocity.properties</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>myVelocity</servlet-name>
<url-pattern>*.vm</url-pattern>
</servlet-mapping>
</web-app>
//velocityServlet.java
public class VelocityServlet extends VelocityViewServlet {
@Override
protected Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context ctx) {
// 往Context容器存放变量
ctx.put("one","这是在Velocity上下文中存放的值");
// 也可以往request域中存值
request.setAttribute("two","这是在request中存放的值");
request.getSession().setAttribute("three","这是在session域中存放的值");
// forward到指定模板
return getTemplate("test.vm");
}
}
//velocity.propertis
## vm文件加载路径,与classpath.resource.loader.path一起作用
## 以下配置是说,从classpath加载vm文件。如果classpath.resource.loader.path=vm,则是从classpath/vm加载vm文件
resource.loader=classpath
classpath.resource.loader.class = org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
## 模板路径,根目录下的vm文件夹
classpath.resource.loader.path = .
## 设置编码
input.encoding = UTF-8
output.encoding = UTF-8
//test.vm
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
${one}
</br>
${two}
</br>
${three}
</br>
</body>
</html>
备注:更多变量设置请参见org.apache.velocity.runtime.defaults.velocity.properties,
这是默认的属性,webapp/WEB-INF/velocity.propertis重写的属性值
## vm从webapp/vm处加载
#resource.loader = webapp
webapp.resource.loader.path = /vm
webapp.resource.loader.class = org.apache.velocity.tools.view.WebappResourceLoader
输入如下所示:
参考文献
【1】http://ifeve.com/apache-velocity-dev/
【2】http://www.jianshu.com/p/ca879cf73883
【3】http://blog.csdn.net/qq_25237663/article/details/52262532
【4】http://velocity.apache.org/engine/devel/developer-guide.html#velocity-and-xml