Jakarta Velocity – 外部ファイルの取り込み
他ファイルのインクルード(静的インクルード)
common_title.txt
共通タイトル #* これはコメントです。 これはコメントです。 *#
テンプレート
#include("common_title.txt")
hello.
実行結果
共通タイトル #* これはコメントです。 これはコメントです。 *# hello.
取り込むファイル内のVTLをVTLとして利用したい場合は#parseを利用する。
他ファイルのインクルード(動的インクルード)
common_title.txt
共通タイトル #* これはコメントです。 これはコメントです。 *#
テンプレート
#parse("common_title.txt")
hello.
実行結果
共通タイトル hello.
インクルード先ファイル内のVTLが有効なため、コメントは出力されていない。
Jakarta Velocity
Velocityとは
あらかじめ用意しておいたテンプレートファイルに、値を動的に設定することができる。
初期設定
バイナリを解凍後、velocity-9.9.jarとvelocity-dep-9.9.jarをビルドパス上に置く。
一覧
- QuickStart!
ファイルの配置〜始めの一歩 - コメント
コメントの利用 - 条件分岐
条件による分岐処理の利用 - 繰り返し
状況に応じた繰り返し処理の利用 - リファレンス表記方法
様々なリファレンス表記方法 - 外部ファイルの取り込み
外部ファイルを取り込む - 解析処理の強制停止
処理を強制停止する
リンク
Jakarta Velocity – QuickStart!(クイックスタート)
QuickStart!
階層

図1:サンプルプログラムの階層
src – Javaソースファイル
template – テンプレートファイル
resource – 設定ファイル等
各ファイル
テンプレートファイル(hello.vm)
■普通に設定
ただいまの時刻は${date}です。
■インスタンスのプロパティ読み込み
${hello.message}
■Listループ
#foreach($str in $hello.messages)
$str
#end
■Arrayループ
#foreach($str in $array)
$str
#end
各書式の動きは以下の通り。具体的なサンプルは後述。
${xxx}:プログラム内で変数を指定することにより、値を設定。
${xxx.xxx}:あるインスタンスのプロパティをゲッター経由で読み出して、値を設定。
#foreach($str in $xxx.xxx)〜#end:あるインスタンスからコレクションをゲッター経由で読み出して、値を設定。
#foreach($str in $xxx)〜#end:配列の要素数分ループして、値を設定。
なお、#foreachのように#から始まる特定の命令はVTL(Velocity Template Language)というVelocity独特の言語である。
プロパティファイル
velocity.properties
resource.loader=class class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader input.encoding=Windows-31J
クラスローダーとエンコードを指定している。
利用するBean
Bean.java
package hello;
import java.util.List;
public class Bean {
private String message;
private List messages;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List getMessages() {
return messages;
}
public void setMessages(List messages) {
this.messages = messages;
}
}
プロパティとセッター&ゲッター
実行クラス
Hello.java
package hello;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
public class Hello {
public static void main(String[] args) throws Exception{
Velocity.init("resource/velocity.properties");
VelocityContext vc = new VelocityContext();
vc.put("date", new Date());
Bean bean = new Bean();
bean.setMessage("hello world");
List list = new ArrayList();
list.add("hello");
list.add("world");
bean.setMessages(list);
vc.put("hello", bean);
String[] array = new String[]{"1.○", "2.△", "3.×"};
vc.put("array", array);
Template template = Velocity.getTemplate("hello.vm");
Writer writer = new OutputStreamWriter(System.out);
template.merge(vc, writer);
writer.close();
}
}
値の設定はVelocityContextのputメソッドで行う。いろいろな型に対応している。
実行結果
■普通に設定 ただいまの時刻はMon May 09 11:35:06 JST 2005です。 ■インスタンスのプロパティ読み込み hello world ■Listループ hello world ■Arrayループ 1.○ 2.△ 3.×

