(1)添加依赖
在maven中添加velocity依赖:
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
(2)创建模板
创建模板first.vm:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
Hello $name,this is my first velocity demo.
</body>
</html>
vm的绝对路径为:D:\code\learn\my-app\first.vm
(3)java实例
package velocity;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Properties;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.junit.Test;
public class VelocityTest {
@Test
public void test() throws IOException {
String vmPath = "D:\\code\\learn\\my-app\\";
Properties p = new Properties();
//指定所有vm文件所在的文件夹路径
p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, vmPath);
p.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
p.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
p.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
VelocityEngine engine = new VelocityEngine(p);
String tempName = "first.vm";
Template template = engine.getTemplate(tempName);
VelocityContext context = new VelocityContext();
context.put("name", "luciffer");
Writer writer = new StringWriter();
template.merge(context, writer);
writer.flush();
System.out.println(writer.toString());
}
}
结果为:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
Hello luciffer,this is my first velocity demo.
</body>
</html>