velocity コードサンプル 2007/01/23
2014/01/26

テンプレートファイルを読み込んで、表示したい。


jakarta commons velocityがいい感じです。
コードはvelocityのサイトにあるチュートリアルをそのまま参考にしています。


import java.io.StringWriter;
import java.util.Properties;

import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.VelocityContext;

public class Test2 {
public static void main(String args[]) throws ResourceNotFoundException,
ParseErrorException, MethodInvocationException, Exception {
Properties prop = new Properties();

// set classpath
prop.setProperty("file.resource.loader.path", "./target/classes/velocity/");
Velocity.init(prop);

VelocityContext context = new VelocityContext();

context.put("name", "Velocity");
context.put("project", "Jakarta");
StringWriter w = new StringWriter();

//
Velocity.mergeTemplate("testtemplate.vm", "utf-8", context, w);
System.out.println(" template : " + w);

String s = "We are using $project $name to render this.";
w = new StringWriter();
Velocity.evaluate(context, w, "mystring", s);
System.out.println(" string : " + w);
}
}

: