创建maven项目
pom.xml
<?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>cn.java3</groupId> <artifactId>java3</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>2.0.0-alpha1</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>2.0.0-alpha1</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.2</version> </dependency> </dependencies> </project>
Java类
package vm; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; 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.ArrayList; import java.util.List; public class HelloWord { public static void main(String[] args){ VelocityEngine ve = new VelocityEngine(); 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()); } }
vm
#set($greet = 'hello') $greet $name #foreach($i in $list) $i #end
运行类即可。
velocity也可以通过手工下载,添加jar到项目里运行,
velocity最新jar包下载地址
http://velocity.apache.org/download.cgi