pxkw.hatenadiary.com

めもめも

Hello Velocity

Velocityのミニマムなコード.
できるだけミニマムに.

HelloVelocity.java

package hello;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

public class HelloVelocity{
	
    public static void say() throws IOException{
    	Velocity.init();
        VelocityContext context = new VelocityContext();
        context.put("name", "Velocity");
        
        Writer   writer  = new StringWriter();
        Template template = Velocity.getTemplate("hello.vtl", "UTF-8");

        template.merge(context, writer);
        System.out.print(writer.toString());
        
        writer.close();
    }

    public static void main(String[] args) throws IOException {
        HelloVelocity.say();
    }
	
}

hello.vtl (テンプレートファイル)

Hello, $name!

実行例

javaコマンドでクラスファイルを実行する例.

.を実行ディレクトリとした時の構成

./hello.vtl
./bin/hello/HelloVelocity.class
/path/to/velocity-X.X-dep.jar

実行コマンドと実行結果

$ java -cp bin:/path/to/velocity-X.X-dep.jar hello.HelloVelocity
Hello, Velocity!
$

備考

テンプレートのパスを指定する場合は, Velocity.init();の前にディレクトリを指定する。

Velocity.setProperty("file.resource.loader.path", "/path/to/dir");

参 考 文 献

一番簡単なApache Velocityの使い方 - KnowledgeFort
Apache Velocity の一番簡単な使用例。