たまに使っても、よく忘れるのでメモ。
VelocityでVMファイルをクラスパスからロードするには、
velocity.properties(名前はなんでもよい)に以下の設定を行う。
resource.loader = class class.resource.loader.class = org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
あと忘れずに、エンコーディングも指定しておく。
input.encoding=Windows-31J output.encoding=Windows-31J
テストクラス。
Velocity.initメソッドに設定したプロパティファイルを渡すこと。
このメソッドに渡すのは、クラスパスリソースではなく、普通のファイルパス。
// vim: set ts=4 sw=4 et ws is nowrap ft=java ff=dos: package gsf.samples.velocity; import java.io.*; import org.apache.velocity.*; import org.apache.velocity.app.*; import org.apache.velocity.exception.*; /** * Velocityのサンプルクラス.<br/> * * @author gsf_zero1 * */ public class VelocitySample001{ private static final String VM_FILE = "gsf/samples/velocity/VelocitySample001.vm"; private static final String VM_ENCODING = "Windows-31J"; public VelocitySample001(){ try{ Velocity.init(this.getClass().getResource("/velocity.properties").getPath()); VelocityContext context = new VelocityContext(); context.put("message", "Velocityのサンプル"); StringWriter sw = new StringWriter(); Template template = Velocity.getTemplate(VM_FILE, VM_ENCODING); // // merge // template.merge(context, sw); System.out.println(sw.toString()); sw.flush(); }catch(Exception ex){ ex.printStackTrace(); } } public static void main(String[] args){ new VelocitySample001(); } }
Velocityに関して、わかりやすく説明されているサイトです。
http://www.techscore.com/tech/ApacheJakarta/Velocity/index.html
================================
過去の記事については、以下のページからご参照下さい。
- いろいろ備忘録日記まとめ
サンプルコードは、以下の場所で公開しています。
- いろいろ備忘録日記サンプルソース置き場