Jakarta Velocity は汎用のテンプレートエンジンです。あらかじめテンプレートファイルを用意しておきそれに変数を仕込んでおいて、プログラムから変数部分のデータを渡してあげることで動的に画面や帳票を作成します。
インストールは Jakarta Velocity よりモジュールをダウンロードし、必要なクラスパスにパスを通すだけです。2006/12/27現在
が直近版みたいです。
やってみます。モデルはUser,CustomerというHibernate/マッピング定義についてで書いたモデルを使用します。Customerは顧客への参照を持ちます。
package nu.mine.kino.velocity; import java.io.StringWriter; import nu.mine.kino.entity.Customer; import nu.mine.kino.entity.User; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import org.apache.velocity.exception.ParseErrorException; import org.apache.velocity.exception.ResourceNotFoundException; public class Main { public static void main(String args[]) { User user = new User(); user.setName("ユーザ1"); user.setAddress("東京都江東区"); Customer c = new Customer(); c.setName("顧客1"); c.setUser(user); //モデルデータの作成完了 try { Velocity.init();// 初期化 VelocityContext context = new VelocityContext(); context.put("user", user);// オブジェクトをセットできるのがおもしろい。 context.put("customer", c); StringWriter out = new StringWriter(); Template template = Velocity.getTemplate("main.vm", "MS932"); template.merge(context, out); System.out.println(out.toString()); out.flush(); } catch (ResourceNotFoundException e) { // TODO 自動生成された catch ブロック e.printStackTrace(); } catch (ParseErrorException e) { // TODO 自動生成された catch ブロック e.printStackTrace(); } catch (Exception e) { // TODO 自動生成された catch ブロック e.printStackTrace(); } } }
お名前:${customer.name} ${customer.name} さまの担当者は${customer.user.name}です。 連絡先:${customer.user.address}
${customer.name}はjavaファイルのcustomerというキー値で渡されたオブジェクトに対応しています。そのオブジェクトのnameプロパティですね。つまり
customer.getName();
てことです。お察しの通り${customer.user.name}は
customer.getUser().getName();
ってことですね。オブジェクトをそのまま渡すことができて、さらにプロパティにアクセスできるのが楽しいです。。
お名前:顧客1 顧客1 さまの担当者はユーザ1です。 連絡先:東京都江東区
なんだかすごく簡単にテンプレート内の値を置換して出力することができました。
この記事は
現在のアクセス:10989