velocity的简单使用
velocity的简单使用
文件目录结构,只有Demo1和hellovelocity.vm有用,其他的只是测试,可忽略
利用代码模板生成需要的代码文件
getPro与getVel区别在于配置的方式不一样
需要更改Template template = ve.getTemplate(“templates/hello.vm”,“UTF-8”);中的模板路径
package com.info33.velocity01.controller;
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;
public class Demo1 {
public static void main(String[] args) {
Demo1 d = new Demo1();
d.getPro();
d.getVel();
}
public void getPro(){
Properties prop = new Properties();
prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
Velocity.init(prop);
VelocityContext ctx = new VelocityContext();
ctx.put("name","张三");
ctx.put("age",18);
Template template = Velocity.getTemplate("templates/hello.vm","UTF-8");
StringWriter sw = new StringWriter();
template.merge(ctx,sw);
System.out.println(sw.toString());
}
public void getVel(){
VelocityEngine ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
ve.init();
VelocityContext ctx = new VelocityContext();
ctx.put("name","张三");
ctx.put("age",18);
Template template = ve.getTemplate("templates/hello.vm","UTF-8");
StringWriter sw = new StringWriter();
template.merge(ctx,sw);
System.out.println(sw.toString());
}
}
所需依赖
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>