VelocityBaseTest.java:
package com.demo.test;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
public class VelocityBaseTest {
public static void main(String[] args) {
try {
//也可使用properites設定,這邊練習不需要
//Velocity.init("properties/velocity.properties");
// 取得velocity上下文
VelocityContext context = new VelocityContext();
context.put("name", "Daniel");
Template template = Velocity.getTemplate("template/hello.vm");
StringWriter writer = new StringWriter();
template.merge(context, writer);
PrintWriter filewriter = new PrintWriter(new FileOutputStream(
"outputTemplate/hello.html"), true);
filewriter.println(writer.toString());
filewriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
hello.vm:
<html>
<head></head>
<body>
HELLO! $name,Welcome to velocity!
</body>
</html>
Velocity.properties:
#Velocity.properties配置示例
# 如果需要系統從WEB-INF/classes路徑載入Velocity的範本檔,取消下兩行的注釋
#resource.loader=class
#class.resource.loader.class=org.apache.Velocity.runtime.resource.loader.ClasspathResourceLoader
#如需禁止系統通過檔案系統載入範本檔,注釋如下兩行
resource.loader=file
file.resource.loader.path=D:\practice\VJ\workspace\velocitytest\template
#確定從何處載入velocity的範本檔
file.resource.loader.cache=false
input.encoding=gb2312
output.encoding=gb2312
產出的檔案:
hello.html:
<html>
<head></head>
<body>
HELLO! sea,Welcome to velocity!
</body>
</html>
沒有留言:
張貼留言