1. Velocity工作流程
- 配置并初始化VelocityEngine 或者Velocity(单例)
- 创建一个context
- 向context中添加变量
- 加载Velocity模版
- Merge 模版和context得到渲染后的结果
Code:
-
目录结构
- helloworld.vm内容:
$hello
- pom:必要的依赖只有一个velocity
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.minxin</groupId>
<artifactId>apache.velocity</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- velocity -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
</dependencies>
</project>
- java代码
package com.velocity.helloworld;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import java.io.StringWriter;
import java.util.Properties;
/**
* @author mingxin
*/
public class Main {
public static void main(String[] args){
Main main = new Main();
main.useVelocity();
}
public void useVelocityEngine(){
try{
VelocityEngine ve = new VelocityEngine();
ve.init(getDefaultProp());
VelocityContext context = new VelocityContext();
context.put("hello", "Hello World!");
StringWriter w = new StringWriter();
Template t = ve.getTemplate("template/helloworld.vm");
t.merge(context, w);
System.out.println("template:" + w);
}catch (Exception e){
e.printStackTrace();
}
}
public void useVelocity(){
try{
Velocity.init(getDefaultProp());
VelocityContext context = new VelocityContext();
context.put("hello", "Hello World!");
StringWriter w = new StringWriter();
Template t = Velocity.getTemplate("template/helloworld.vm");
t.merge(context, w);
System.out.println("template:" + w);
}catch (Exception e){
e.printStackTrace();
}
}
public Properties getDefaultProp(){
Properties prop = new Properties();
prop.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
prop.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
return prop;
}
}
2.遇到的问题
2.1 找不到模版路径
严重: ResourceManager : unable to find resource 'helloworld.vm' in any resource loader.
不管是用VelocityEngine还是用Velocity在init之前都需要配置一下资源加载器。参考解决方法
public Properties getDefaultProp(){
Properties prop = new Properties();
prop.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
prop.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
return prop;
}