注:本站所有项目均使用maven构建!
创建maven项目,目录结构
pom.xml引用jar包
<!-- velocity --> <dependency> <groupId>com.e-rimming.third</groupId> <artifactId>velocity</artifactId> </dependency> <dependency> <groupId>com.e-rimming.third</groupId> <artifactId>velocity-tools</artifactId> </dependency> <!-- apache --> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> </dependency>
其中 apache的几个jar是单独使用Velocity的依赖。
Single类对应的主方法
public static void main(String[] args) throws Exception { // 获取Velocity对象并准备数据 Velocity.init(); VelocityContext ctx = new VelocityContext(); ctx.put("name", new String("world")); // 获取模版并执行 Template tem = null; tem = Velocity.getTemplate("src/main/resources/single.vm"); StringWriter writer = new StringWriter(); tem.merge(ctx, writer); // 输出控制台 System.out.println(writer.toString()); // 输出流到文件 PrintWriter filewriter = new PrintWriter(new FileOutputStream("/Users/kk/Desktop/single.html"), true); filewriter.print(writer.toString()); filewriter.close(); }
single.vm
hello $name
Single.java main方法运行结果
hello world
类Single会在对应的目录下生成一个html文件。