2009年10月27日

Apache Velocity StringResourceLoader and GenericTools

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.runtime.resource.loader.StringResourceLoader;
import org.apache.velocity.runtime.resource.util.StringResourceRepository;
import org.apache.velocity.tools.generic.DateTool;

public class Main {

public static void main(String[] args) throws Exception {
Velocity.setProperty("resource.loader", "string");
Velocity.setProperty("string.resource.loader.class",
"org.apache.velocity.runtime.resource.loader.StringResourceLoader");
Velocity.setProperty("string.resource.loader.repository.class",
"org.apache.velocity.runtime.resource.util.StringResourceRepositoryImpl");
Velocity.init();

StringWriter templateString = new StringWriter();
PrintWriter pw = new PrintWriter(templateString);

pw.println(" Name: $name");
pw.println(" Age: $age");
pw.println("birthday: $date.format('yyyy-MM-dd', $birthday)");

StringResourceRepository repo = StringResourceLoader.getRepository();
repo.putStringResource("test.vm", templateString.getBuffer().toString());

Template template = Velocity.getTemplate("test.vm");

VelocityContext context = new VelocityContext();
context.put("date", new DateTool());

context.put("name", "Solnone");
context.put("age", new Integer(37));
Date birthday = new Date();
context.put("birthday", birthday);

StringWriter sw = new StringWriter();
template.merge(context, sw);
System.out.println(sw);

}

}

沒有留言:

網誌存檔