Velocity

Velocityについて

コミュニティ

ドキュメント

ツール

比較

日本語訳について

Contents − 目次

  1. Introduction and Getting Started
  2. Resources
  3. How Velocity Works
  4. To Singleton Or Not To Singleton...
  5. The Context
  6. Using Velocity in Servlets
  7. Using Velocity in General Applications
  8. Application Attributes
  9. EventCartridge and Event Handlers
  10. Velocity Configuration Keys and Values
  11. Configuring the Log System
  12. Configuring the Resource Loaders (template loaders)
  13. Template Encoding for Internationalization
  14. Velocity and XML
  15. FAQ (Frequently Asked Questions)
  16. Summary
  17. Appendix 1 : Deploying the Example Servlet

  1. はじめに
  2. リソース
  3. Velocity の動作原理
  4. Singletonにすべきか否か…
  5. コンテキスト
  6. サーブレットで Velocity を使う
  7. 一般的なアプリケーションで Velocity を使う
  8. アプリケーション属性
  9. EventCartridge とイベントハンドラ
  10. Velocity 設定キーと値
  11. ログシステム設定
  12. リソースローダの設定
  13. 国際化のためのテンプレートエンコーディング
  14. Velocity と XML
  15. FAQ (よく聞かれる質問)
  16. まとめ
  17. 追記 1:サンプルサーブレットの配備


Introduction − はじめに

Velocity is a Java-based template engine, a simple and powerful development tool that allows you to easily create and render documents that format and present your data. In this guide, we hope to give an overview of the basics of development using Velocity, focusing on the two main areas for Velocity usage :

Velocity は、Java ベースのテンプレートエンジンであり、 データをフォーマット・表示する文書を簡単に作成・提供するための単純で強力な開発ツールです。 このガイドでは、 Velocity の主な用途である以下の2つの領域に焦点を当てながら、 Velocity を使用した開発の基本概要について説明したいと思います。

  • servlet-based WWW development
  • general application use
  • サーブレットベースの WWW 開発
  • 一般的なアプリケーションでの使用

You will see that there is no real difference between these, other than we make servlet development with Velocity very easy if you use our provided class VelocityServlet as a base class for your servlet, and offer a utility class to help with application development.

両者は本質的には違いはないことが分かると思います。あえて違いがあるとすれば、 サーブレット開発では基本クラスとして我々の提供する VelocityServlet を使うと簡単になるのと、 アプリケーション開発で役立つユーティリティクラスを提供していることぐらいでしょう。

Getting Started

導入

While this information is found elsewhere on the Velocity site and in the documentation, it is included here for completeness. Getting Velocity running on your computer is very easy. Note that all directory references are relative the root of the Velocity distribution tree.

  1. Get the Velocity distribution. This is available as a release, nightly snapshot or directly from the CVS code repository. Any are fine, although for the latest features, the nightly snapshot is most likely the best way. For more information, go here.
  2. If you don't have Jakarta Ant, the Java build tool already installed, please do so. It is required for building Velocity, although not required for using Velocity.
  3. Go to the build directory in the distribution.
  4. Type ant <build target> where <build target> is one of:
    • jar builds the complete Velocity jar in the bin directory. This jar will be called 'velocity-X.jar', where 'X' is the current version number. This jar does not include necessary dependencies for Velocity. If you use this target, you must get the Collections component jar from Jakarta Commons and add to your CLASSPATH (or WEB-INF/lib). If you wish to use the built-in logging or template conversion, you must include the appropriate jars in your CLASSPATH or webapp's WEB-INF/lib. For convenience, you can use the jar-dep target to build a jar with ORO, Logkit and Commons Collections included.
    • jar-dep builds the complete Velocity jar in the bin directory, including necessary support for logging from the Jakarta Avalon Logkit package, critical configuration support from the Jakarta Commons and the necesary support for WebMacro template conversion using the Jakarta ORO package.
    • jar-core builds a slimmer Velocity jar in the bin directory, called 'velocity-core-X.jar'. This jar contains the core Velocity functionality, and doesn't include example and utility things like Anakia, Texen or the VelocityServlet support baseclass. It has the same external dependency requirements as the regular jar target.
    • jar-util builds a utility Velocity jar in the bin directory, called 'velocity-util-X.jar'. This jar contains utility code, specifically Anakia, Texen, and the WebMacro template conversion utility. It has the same external dependency requirements as the regular jar target.
    • jar-servlet builds a utility Velocity jar in the bin directory, called 'velocity-servlet-X.jar'. This jar contains utility code for servlet programmers. It has the same external dependency requirements as the regular jar target.
    • jar-J2EE builds a complete jar, like the 'jar' target, that includes any components that require J2EE support. Currently, this includes only org.apache.velocity.runtime.resource.loader.DataSourceResourceLoader. As usual, it is placed in the bin directory, called 'velocity-j2ee-X.jar'. NOTE : if you wish to use this build target, you must place (or link) a copy of j2ee.jar into the build/lib directory. We do not provide it as part of the distribution. A good source is http://java.sun.com/. It has the same external dependency requirements as the regular jar target.
    • jar-J2EE-dep build a complete jar with J2EE support and includes logging support from the Jakarta Avalon Logkit and regexp support fromt the Jakarta ORO package. See the notes on the jar-dep target, above.
    • examples builds the example code in the example programs found in the examples directory. This build target will also build the forumdemo example project.
    • forumdemo builds the example webapplication in the examples/forumdemo directory.
    • docs builds these docs in the docs directory using Velocity's Anakia XML transformation tool. Allowing you to use Velocity templates in place of stylesheets - give it a try! Note: This target requires that the jakarta-site2 project is located as a peer directory to the jakarta-velocity distribution directory. Please see the note in the build.xml file for this target for further information.
    • jar-src bundles all the Velocity source code into a single jar, placed in the bin directory.
    • javadocs builds the Javadoc class documentation in the docs/api directory
    • test (after jar) will test Velocity against it's testbed suite of test routines
    • help lists the build targets that are available.
  5. While not required, testing the build is a good idea. Use the test target mentioned above.
  6. That's it! Velocity is ready to be used. Put the jar into your classpath, or into other appropriate places (such as the lib directory of your webapp if using with servlets)
  7. If you want to play with the examples, which is highly recommended when getting started, use build the examples via ant examples.

この情報は Velocity サイト上や文書内の他の場所にもありますが、 念のために、ここでも記述しています。 Velocity をあなたのコンピュータで動かすのは、非常に簡単です。 なお、全てのディレクトリの参照は、 Velocity 配布のルートディレクトリを基準にしていますのでご注意ください。

  1. Velocity 配布を入手します。 リリース版や、夜間スナップショットとしても入手できますし、直接 CVS コードリポジトリからも入手可能です。 どれでも構いませんが、最新の機能なら、夜間スナップショットがおそらく一番良いでしょう。 詳細情報は、こちらを参照してください。
  2. Java 構築ツールの Jakarta Ant を まだインストールしていない場合には、まずそれをインストールしてください。 Velocity を使用するには必要ありませんが、Velocity を構築するのに必要です。
  3. 配布の build ディレクトリに移動します。
  4. ant <build target> とタイプします。<build target> は以下のうちのどれかです。
    • jar bin ディレクトリに Velocity の完全版の jar ファイルを構築します。jar ファイルは、'velocity-X.jar' という名前で、 「X」は、現在のバージョン番号です。このjarファイルにはVelocity で必要なコンポーネントは含まれていません。このターゲットを使う場合は、 Jakarta Commons から Collections コンポーネントを入手し、クラスパス (あるいは WEB-INF/lib)に追加する必要があります。 ビルドインされたログ機能やテンプレート変換機能を使いたい場合は、 クラスパスか Web アプリケーションの WEB-INF/lib に jar ファイルを適宜含めなければなりません。 便宜上、ORO、Logkit、Commons Collections を含めた jar ファイルを構築できる jar-dep タスクを使うこともできます。
    • jar-dep bin ディレクトリに Velocity の完全版の jar ファイルを構築します。この jar ファイルには、 Jakarta Avalon Logkit パッケージによるロギングに必要なサポートや、 Jakarta Commons による重要な設定のサポートや、 Jakarta ORO パッケージを使った WebMacro テンプレート変換に必要なサポートが含まれています。
    • jar-core bin ディレクトリにサイズの小さな「velocity-core-X.jar」という 名前のVelocity JAR ファイルを構築します。この JAR ファイルには、Velocity 機能のコアが含まれていますが、サンプルや、Anakia、Texen、VelocityServlet をサポートする基本クラスといったユーティリティは含まれていません。
    • jar-util bin ディレクトリに「velocity-util X.jar」という名前の ユーティリティ Velocity JAR ファイルを 構築します。この JAR ファイルには、 Anakia、Texen 、 WebMacro テンプレート変換ユーティリティといった、 ユーティリティのコードが入っています。通常の jar ターゲットと同様の外部依存が必要です。
    • jar-servlet bin ディレクトリに「velocity-servlet X.jar」という名前の ユーティリティ Velocity jar ファイルを構築します。この jar ファイルには、 サーブレットプログラマ向けのユーティリティのコードがあります。 通常の jar ターゲットと同様の外部依存が必要です。
    • jar-j2ee 「jar」ターゲットと同様に、 J2EE サポートを必要とするすべてのコンポーネントが含まれている、 完全な jar を構築します。現在のところ、 org.apache.velocity.runtime.resource.loader.DataSourceResourceLoader だけしか含まれません。他のものと同様に、「velocity-j2ee-X.jar」という名前で、 bin ディレクトリに置かれます。注意: この構築ターゲットを使用したいときには、build/lib ディレクトリに j2ee.jar のコピー(またはリンク)を置かなければなりません。我々は、 配布の一部としてそれを提供していません。取得元としては、 http://java.sun.com/ が良いしょう。通常の jar ターゲットと同様の外部依存が必要です。
    • jar-J2EE-dep J2EE をサポートする完全な jar ファイルを構築し、Jakarta Avalon Logkit によるロギングサポートや、Jakarta ORO パッケージによる正規表現サポートが含まれています。上記の jar-dep ターゲットでの注意もご覧下さい。
    • examples examples ディレクトリにあるプログラムサンプルのコードを構築します。 このターゲットは forumdemo プロジェクトも構築します。
    • forumdemo examples/forumdemo ディレクトリにサンプル Web アプリケーションを 構築します。
    • docs Velocity の Anakia XML 変換ツールを使用して 今ご覧のドキュメントを docs ディレクトリに構築します。 スタイルシートの代わりに Velocity テンプレートを使うことができます。 ── 一度お試しください! 注意:このターゲットでは、 jakarta-site2 プロジェクトのディレクトリが jakarta-velocity 配布ディレクトリと同じディレクトリの下にある必要があります。 このターゲットについての詳細は build.xml ファイルをご覧ください。
    • jar-src 全ての Velocity ソースコードを一つの jar にまとめ、 bin ディレクトリに置きます。
    • javadocs docs/api ディレクトリに Javadoc クラスドキュメントを構築します。
    • test (jar タスクのあとで) テストルーチンの testbed スイートに対して Velocity のテストを行ないます。
    • help 利用できる構築ターゲットの一覧を表示します。
  5. ビルドのテストは必要ではありませんが、するに越したことはないでしょう。 上記の test ターゲットを使ってください。
  6. これで、 Velocity を、使用する準備ができました。JAR ファイルを、 クラスパスなどの適切な場所(サーブレットで使うのなら、 Webアプリケーションの lib ディレクトリとか)に置きます
  7. サンプルを試してみたいという場合(はじめての場合には特に推奨します)には、 ant examples でサンプルを構築してください。

Dependencies 依存関係

Velocity uses elements of the Java 2 API such as collections, and therefore building requires the Java 2 Standard Edition SDK (Software Development Kit). To run Velocity, the Java 2 Standard Edition RTE (Run Time Environment) is required (or you can use the SDK, of course).

Velocity ではコレクションなど Java 2 API を使っているので、ビルドには Java 2 Standard Edition SDK (Software Development Kit) が必要です。 Velocity を実行するには、Java 2 Standard Edition RTE (Run Time Environment) (もちろん SDK でも可) が必要です。

Velocity also is dependent upon a few packages for general functionality. They are included in the build/lib directory for convenience, but the default build target (see above) does not include them. If you use the default build target, you must add the dependencies to your classpath.

Velocity はまた、汎用的な機能に関していくつかのパッケージに依存しています。 これらのパッケージは便宜上、build/lib に入っています。 しかし、デフォルトのビルドターゲット(上述)には入っていません。 デフォルトのビルドターゲットを使う場合は、 クラスパスにこの依存関係を加えなければなりません。

  • Jakarta Commons Collections ─ 必須です。
  • Jakarta Avalon Logkit ─ オプションですが、非常に一般的です。 Velocityで、デフォルトのファイルベースのロギングを使う場合に必要です。
  • Jakarta ORO ─ オプションです。org.apache.velocity.convert.WebMacro テンプレート変換ユーティリティを使う場合に必要です。


Resources − リソース

There are quite a few resources and examples available to the programmer, and we recommend that you look at our examples, documentation and even the source code. Some great sources are :

かなりの数のリソースやサンプルをプログラマは利用できます。 サンプルやドキュメント、できればソースコードもチェックすることをお勧めします。 素晴らしいソースをいくつか紹介しましょう。

  • The user and developer community : join us via the mail-lists.
  • Mail-list archives : http://www.mail-archive.com is a good one. Type 'velocity' into the search box to see both our -user and -dev archives.
  • source code : src/java/... : all the source code to the Velocity project
  • application example 1 : examples/app_example1 : a simple example showing how to use Velocity in an application program.
  • application example 2 : examples/app_example2 : a simple example showing how to use Velocity in an application program using the Velocity application utility class.
  • servlet example : examples/servlet_example1 : a simple example showing how to use Velocity in a servlet.
  • logger example : examples/logger_example : a simple example showing how to create a custom logging class and register it with Velocity to receive all log messages.
  • XML example : examples/xmlapp_example : a simple example showing how to use JDOM to read and access XML document data from within a Velocity template. It also includes a demonstration of a recursive Velocimacro that walks the document tree.
  • event example : examples/event_example : An example that demonstrates the use of the event handling API in Velocity 1.1
  • Anakia application : examples/anakia : example application showing how to use Velocity for creating stylesheet renderings of xml data
  • Forumdemo web app : examples/forumdemo : working example of a simple servlet-based forum application
  • documentation : docs : all the generated documentation for the Velocity project in html
  • API documentation : docs/api : the generated Javadoc documentation for the Velocity project
  • templates : test/templates : a large collection of template examples in our testbed directory, these are a great source of useage examples of VTL, the Velocity Template Language
  • context example : examples/context_example : two examples showing how the Velocity context can be extended. For advanced users.
  • ユーザコミュニティと開発者コミュニティ : メーリングリスト から参加してください。
  • メーリングリスト・アーカイブ : http://www.mail-archive.com は、そのひとつです。 velocity-user、 velocity-devの両方のアーカイブを見るには、検索フィールドに 'velocity' と入力してください。
  • ソースコード : src/java/… : Velocity プロジェクトのすべてのソースコードがあります。
  • アプリケーションサンプル 1 : examples/app_example1 : アプリケーションプログラムでの Velocity の使い方を示した簡単なサンプル。
  • アプリケーションサンプル 2 : examples/app_example2 : Velocity アプリケーション ユーティリティクラスを使用したアプリケーション プログラムの簡単なサンプル。
  • サーブレットサンプル : examples/servlet_example1 : サーブレットでの Velocity の使い方を示した簡単なサンプル。
  • ロガーサンプル : examples/logger_example : カスタムロギングクラスを作成し、全てのログメッセージを受信できるように Velocity に登録する方法を示す簡単なサンプル。
  • XML サンプル : examples/xmlapp_example : JDOM を使って、Velocity テンプレート内から XML ドキュメントデータを読み込んでアクセスする方法を示す簡単なサンプル。 ドキュメントツリーを探索するための再帰的な Velocimacro デモも含まれています。
  • イベントサンプル : examples/event_example : Velocity 1.1 の イベントハンドリングAPIを使い方をデモするサンプル。
  • Anakia アプリケーション : examples/anakia : Velocityを使って、XML データを処理するスタイルシートを作る方法 を示すサンプルアプリケーション。
  • フォーラムデモ Web アプリ : examples/forumdemo : 単純なサーブレットベースのフォーラムアプリケーションの動作サンプル。
  • ドキュメンテーション : docs : html で生成されたVelocityプロジェクトの全てのドキュメント。
  • API ドキュメント : docs/api : 生成された、Velocity プロジェクトの Javadoc ドキュメント
  • 各種テンプレート : test/templates : testbed ディレクトリ内には、テンプレートサンプルがたくさん入っています。 VTL (Velocity Template Language) の使い方についてのすばらしい情報源となるでしょう。
  • コンテキストサンプル : examples/context_example : Velocity コンテキストの拡張方法を示した2つのサンプルがあります。 上級者向け。

All directory references above are relative to the distribution root directory.

上記の全てのディレクトリは、配布ルートディレクトリからの相対パスとなっています。


How Velocity Works − Velocity の動作原理

'The Fundamental Pattern'

「基本パターン」

When using Velocity in an application program or in a servlet (or anywhere, actually), you will generally do the following :

アプリケーションプログラムやサーブレットで Velocity を使う場合 (実際のところ、どこで使う場合も)、通常は以下のことを行なう必要があります。

  1. Initialize Velocity. This applies to both usage patterns for Velocity, the Singleton as well as the 'separate runtime instance' (see more on this below), and you only do this once.
  2. Create a Context object (more on what that is later).
  3. Add your data objects to the Context.
  4. Choose a template.
  5. 'Merge' the template and your data to produce the ouput.
  1. Velocity を初期化します。 これは、Singleton と、「分離実行時インスタンス」(詳細については下記参照) という Velocity の利用パターンの両方に適用され、一度だけ行なう必要があります。
  2. Context オブジェクトを生成します (詳細は後述)。
  3. データオブジェクトを Context に追加します。
  4. テンプレートを選択します。
  5. 出力を生成するためにデータとテンプレートを「マージ」します。

In code, using the singleton pattern via the org.apache.velocity.app.Velocity class, this looks like

org.apache.velocity.app.Velocity クラスから Singleton パターンを使用する場合、 コードではこんな風になります。

import java.io.StringWriter;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.MethodInvocationException;

Velocity.init();

VelocityContext context = new VelocityContext();

context.put( "name", new String("Velocity") );

Template template = null;

try
{
   template = Velocity.getTemplate("mytemplate.vm");
}
catch( ResourceNotFoundException rnfe )
{
   // couldn't find the template
}
catch( ParseErrorException pee )
{
  // syntax error : problem parsing the template
}
catch( MethodInvocationException mie )
{
  // something invoked in the template
  // threw an exception
}
catch( Exception e )
{}

StringWriter sw = new StringWriter();

template.merge( context, sw );

import java.io.StringWriter;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.ResourceNotFoundException; 
import org.apache.velocity.exception.ParseErrorException; 
import org.apache.velocity.exception.MethodInvocationException; 

Velocity.init();

VelocityContext context = new VelocityContext();

context.put( "name", new String("Velocity") );

Template template = null;

try
{
   template = Velocity.getTemplate("mytemplate.vm");
}
catch( ResourceNotFoundException rnfe )
{
   // テンプレートが見つからない
}
catch( ParseErrorException pee )
{
  // 構文エラー : テンプレートの解析時に問題発生
}
catch( MethodInvocationException mie ) 
{ 
  // テンプレートのどこかで例外が投げられた
} 
catch( Exception e )
{}

StringWriter sw = new StringWriter();

template.merge( context, sw );

That's the basic pattern. It is very simple, isn't it? This is generally what happens when you use Velocity to render a template. You probably won't be writing code exactly like this - we provide a few tools to help make it even easier than this for both servlet and application programmers. Later on in this guide, we will talk about using Velocity in both servlets as well as general applications, and we discuss the tools we provide to make things easier. In each case, though, the above sequence is what is happening either explicitly, or behind the scenes.

これが、基本的なパターンです。とっても単純ですよね? これが、 テンプレート処理で Velocity を使うときに通常行なうことです。 たぶん、ここまで厳密にコードを書くことにはならないでしょう ── サーブレットプログラマとアプリケーションプログラマの両方に対して、 より簡単にするためのいくつかのツールを用意しています。 このガイドの後の方で、サーブレットと一般的なアプリケーションの両方での Velocity の使い方について説明し、 より簡単にするために我々が提供するツールについて説明します。 しかし、どちらの場合でも上記のような処理が、 表立って、あるいは舞台裏で行われているのです。


To Singleton Or Not To Singleton... − Singletonにすべきか否か…

As of Velocity 1.2 and later, developers now have two options for using the Velocity engine, the singleton model and the separate instance model. The same core Velocity code is used for both approaches, which are provided to make Velocity easier to integrate into your Java application.

Velocity 1.2 からは、Velocity エンジンを使うにあたって、開発者には Singleton モデルと分離インスタンスモデルの 2 つの選択肢があります。 どちらの方法でも同じコアの Velocity コードを使用し、どちらの方法でも Velocity を簡単に Java アプリケーションに統合できます。

Singleton Model

Singleton モデル

This is the legacy pattern, where there is only one instance of the Velocity engine in the JVM (or web application, depending) that is shared by all. This is very convenient as it allows localized configuration and sharing of resources. For example, this is a very appropriate model for use in a Servlet 2.2+ compliant web application as each web application can have it's own instance of Velocity, allowing that web application's servlet to share resources like templates, a logger, etc. The singleton is accessable via the org.apache.velocity.app.Velocity class, and and example of use :

これは従来のパターンで、JVM (場合によっては Webアプリケーション) 内にただ一つの Velocity エンジンのインスタンスがあり、これを全体で共有します。 設定をローカライズしたり、リソースを共有することができるので、とても便利です。 例えば、このパターンはサーブレット2.2 以降に準拠した Web アプリケーションで使用するのに適切なモデルです。なぜなら、 各 Web アプリケーションが独自の Velocity のインスタンスを持つため、 Web アプリケーションのサーブレットは、テンプレート、ロガーといったリソースを共有できるからです。 Singleton は、org.apache.velocity.app.Velocity クラスからアクセス でき、以下の例のように使用します。


import org.apache.velocity.app.Velocity;
import org.apache.velocity.Template;

...

/*
 *  Configure the engine - as an example, we are using
 *  ourselves as the logger - see logging examples
 */

Velocity.setProperty( Velocity.RUNTIME_LOG_LOGSYSTEM, this);

/*
 *  now initialize the engine
 */

Velocity.init();

...

Template t = Velocity.getTemplate("foo.vm");
 

import org.apache.velocity.app.Velocity; 
import org.apache.velocity.Template; 

(中略) 
/* 
 *  エンジンの設定 ─ サンプルとして、このクラスそのものを
 *  ロガーとして使っています ─ ロギングサンプルを参照
 */ 
Velocity.setProperty( Velocity.RUNTIME_LOG_LOGSYSTEM, this); 
/* 
 *  ここで、エンジンを初期化します
 */ 
Velocity.init(); 

(中略) 

Template t = Velocity.getTemplate("foo.vm"); 

Please note that the Singleton model is used in the org.apache.velocity.servlet.VelocityServlet base class, a utility class provided with the distribution to make writing servlets easier. While extending this class is the most common and convenient way to write servlets using Velocity, you are free to not use this class if you needs require something different.

Singleton モデルは、 org.apache.velocity.servlet.VelocityServlet という基本クラスでも使われていることに注意してください。 このクラスはサーブレットを簡単に作成するためにこの配布で提供されている ユーティリティクラスです。 このクラスを拡張するのが、Velocity を使ったサーブレットを開発する際に最も一般的で便利な方法ですが、 何か別のものが必要ならばこのクラスを使わないことも可能です。

Separate Instance

分離インスタンス

New in version 1.2, the separate instance allows you to create, configure and use as many instances of Velocity as you wish in the same JVM (or web application.) This is useful when you wish to support separate configurations, such as template directories, loggers, etc in the same application. To use separate instances, use the org.apache.velocity.app.VelocityEngine class. An example, which parallels the above singleton example, looks like :

バージョン 1.2 から、分離インスタンスによって、同一のJVM (または Web アプリケーション) 内で Velocity インスタンスを欲しいだけ生成・設定・使用できます。 テンプレートディレクトリやロガーなどのように、同じアプリケーションで 別々の構成をサポートしたいときに役に立ちます。分離インスタンスを使用するには、 org.apache.velocity.app.VelocityEngine クラスを使用します。 上記の Singleton の例と似たような例があります。


import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.Template;

...

/*
 *  create a new instance of the engine
 */

VelocityEngine ve = new VelocityEngine();

/*
 *  configure the engine.  In this case, we are using
 *  ourselves as a logger (see logging examples..)
 */

ve.setProperty( VelocityEngine.RUNTIME_LOG_LOGSYSTEM, this);

/*
 *  initialize the engine
 */

ve.init();

...

Template t = ve.getTemplate("foo.vm");
 
    
import org.apache.velocity.app.VelocityEngine; 
import org.apache.velocity.Template; 

(中略) 

/*
 * 新たなエンジンのインスタンスを生成
 */

VelocityEngine ve = new VelocityEngine(); 

/*
 * エンジンの設定。この場合、このクラスそのものを、
 * ロガーとして使用しています(ロギングサンプルを参照)。
 */

ve.setProperty( VelocityEngine.RUNTIME_LOG_LOGSYSTEM, this); 

/*
 * エンジンを初期化
 */

ve.init(); 
 
(中略) 

Template t = ve.getTemplate("foo.vm"); 

As you can see, this is very simple and straightforward. Except for some simple syntax changes, using Velocity as a singleton or as separate instances requires no changes to the high-level structure of your application or templates.

ごらんのように、これはとても単純でストレートです。 幾つかの単純な構文の変更を除いて、 Singleton にせよ分離インスタンスにせよ、 Velocity を使う時にアプリケーションやテンプレートの高レベルの構造を 変更する必要はありません

As a programmer, the classes you should use to interact with the Velocity internals are the org.apache.velocity.app.Velocity class if using the singleton model, or org.apache.velocity.app.VelocityEngine if using the non-singleton model ('separate instance').

プログラミングの際に Velocity 内部と情報をやり取りするのに使うクラスは、 Singleton モデルを使用するなら org.apache.velocity.app.Velocity で、 Singleton でないモデル(「分離インスタンス」)を使用するなら org.apache.velocity.app.VelocityEngine です。

At no time should an application use the internal Runtime, RuntimeConstants, RuntimeSingleton or RuntimeInstance classes in the org.apache.velocity.runtime package, as these are intended for internal use only and may change over time. As mentioned above, the classes you should use are located in the org.apache.velocity.app package, and are the Velocity and VelocityEngine classes. If anything is missing or needed from those classes, do not hesitate to suggest changes - these classes are intended for the application developer.

アプリケーションでは、org.apache.velocity.runtime パッケージの RuntimeRuntimeConstantsRuntimeSingletonRuntimeInstance の各クラスは絶対に使わないでください。 これらは内部使用のみを想定しており、いつか変更される可能性があります。 上で説明したとおり、使うべきクラスは org.apache.velocity.app パッケージにある、Velocity クラスと VelocityEngine クラスです。これらのクラスに何かが抜けていたり何かが必要ならば、 ためらわずに変更点を提案して下さい ─ これらのクラスはアプリケーション開発者向けのものです。


The Context − コンテキスト
The Basics 基本

The concept of the 'context' is central to Velocity, and is a common technique for moving a container of data around between parts of a system. The idea is that the context is a 'carrier' of data between the Java layer (or you the programmer) and the template layer ( or the designer ). You as the programmer will gather objects of various types, whatever your application calls for, and place them in the context. To the designer, these objects, and their methods and properties, will become accessable via template elements called references. Generally, you will work with the designer to determine the data needs for the application. In a sense, this will become an 'API' as you produce a data set for the designer to access in the template. Therefore, in this phase of the development process it is worth devoting some time and careful analysis.

「コンテキスト」という概念は、Velocity の核となるもので、システムの各部分の間で、 データのコンテナ(入れ物)をやり取りするのに一般的なテクニックです。 つまり、コンテキストは、 Java 層 (またはプログラマ) とテンプレート層 (またはデザイナ) の間でのデータの「運び屋」だということです。 プログラマは、アプリケーションで必要な色々なタイプのオブジェクトを集めて、 コンテキストに設定します。デザイナの方では、これらのオブジェクト、 あるいはそのメソッドやプロパティは、リファレンス と呼ばれるテンプレート要素でアクセスできます。 一般的に、プログラマはデザイナと一緒にアプリケーションでのデータ要件を決めます。 ある意味ではこの要件が、デザイナがテンプレートでアクセスできるデータセットを生成する 「API」となります。ですから、開発プロセスのこのフェーズではある程度時間を割いて 慎重な分析を行なうだけの意味があります。

While Velocity allows you to create your own context classes to support special needs and techniques (like a context that accesses an LDAP server directly, for example), a good basic implementation class called VelocityContext is provided for you as part of the distribution.

Velocityを使うと、特別な要件やテクニック (例えばLDAPサーバに直接アクセスする コンテキストとか) をサポートする自分用のコンテキストクラスを作ることもできますが、 配布の一部として、VelocityContext という良く出来た基本的な実装クラスが用意されています。

VelocityContext is suitable for all general purpose needs, and we strongly recommended that you use it. Only in exceptional and advanced cases will you need to extend or create your own context implementation.

VelocityContext はあらゆる汎用的な用途に適しており、使用を強く推奨します。 自分用のコンテキスト実装を拡張または作成する必要があるのは例外的で高度な場合のみです。

Using VelocityContext is as simple as using a normal Java Hashtable class. While the interface contains other useful methods, the two main methods you will use are

VelocityContext の使い方は、通常の Java の Hashtable クラスを使用するのと 同じくらい単純です。このインタフェースには便利なメソッドがいろいろありますが、 主に使うメソッドは以下の2つです。

public Object put(String key, Object value);
public Object get(String key);

Please note that like a Hashtable, the value must be derived from java.lang.Object, and must not be null. Fundamental types like int or float must be wrapped in the appropriate wrapper classes.

HashTable と同様に、値は java.lang.Object から派生しており、null は禁止されていることに注意して下さい。 int や float といった基本タイプは適宜ラッパクラスでラップしなければなりません。

That's really all there is to basic context operations. For more information, see the API documentation included in the distribution.

基本的なコンテキストの操作方法は本当にこれで全てです。詳細については配布に含まれている APIドキュメントをご覧下さい。

Support for Iterative Objects for #foreach()

#foreach() での繰り返しオブジェクトのサポート

As a programmer, you have great freedom in the objects that you put into the context. But as with most freedoms, this one comes with a little bit of responsibility, so understand what Velocity supports, and any issues that may arise. Velocity supports serveral types of collection types suitable for use in the VTL #foreach() directive.

プログラマであれば、コンテキストへのオブジェクトの設定を極めて自由に行なえます。 しかし、他の大部分の自由と同様に、この自由にも少しですが責任がついてきます。 そのためには、 Velocity のサポート対象とそれによって起こる問題を理解する必要があります。 Velocity は VTL の #foreach() 指示子で使うのに適した、 何種類かのコレクション型をサポートしています。

  • Object [] Regular object array, not much needs to be said here. Velocity will internally wrap your array in a class that provides an Iterator interface, but that shouldn't concern you as the programmer, or the template author.
  • java.util.Collection Velocity will use the iterator() method to get an Iterator to use in the loop, so if you are implementing a Collection interface on your object, please ensure that iterator() returns a working Iterator.
  • java.util.Map Here, Velocity depends upon the values() method of the interface to get a Collection interface, on which iterator() is called to retrieve an Iterator for the loop.
  • java.util.Iterator USE WITH CAUTION : This is currently supported only provisionally - the issue of concern is the 'non-resettablity' of the Iterator. If a 'naked' Iterator is placed into the context, and used in more than one #foreach(), subsequent #foreach() blocks after the first will fail, as the Iterator doesn't reset.
  • java.util.Enumeration USE WITH CAUTION : Like java.util.Iterator, this is currently supported only provisionally - the issue of concern is the 'non-resettablity' of the Enumeration. If a 'naked' Enumeration is placed into the context, and used in more than one #foreach(), subsequent #foreach() blocks after the first will fail, as the Enumeration doesn't reset.
  • Object[] 通常のオブジェクト配列。特に説明の必要はないでしょう。 Velocity 内部では、Iterator インタフェースを備えたクラスで配列をラップしますが、 プログラマやテンプレート作者としてそれを気にする必要はありません。
  • java.util.Collection Velocity ではループで使う Iterator を 取得するのに iterator() メソッドを使用します。 したがってオブジェクトで Collection インタフェースを実装する場合は 正しく動作する Iterator を iterator() が返すことを確認してください。
  • java.util.Map この場合、Velocity は、インタフェースメソッドの values() を使います。これは、ループで Iterator を取り出すために呼ばれる iterator() メソッドを持つ Collection インタフェースを取得するためです。
  • java.util.Iterator 使用上の注意: 今のところ条件つきでのみサポートされています ─ 懸念されるのは Iterator が 「リセット不可」であることです。もし Iterator が「何も着けずに」 [訳注:他の型を経由せずに] コンテキストに設定されて #foreach() で2回以上使われる場合、 Iterator はリセットされないので、2回目以降の #foreach() ブロックでは失敗します。
  • java.util.Enumeration 使用上の注意: java.util.Iterator と同様に、今のところ条件つきでサポートされています ─ 懸念されるのは Enumeration が「リセット不可」であることです。もし Enumeration が「何も着けずに」コンテキストに設定されて #foreach() で2回以上使われる場合、 Enumerationはリセットされないので、2回目以降の #foreach() ブロックでは失敗します。

In the case of the Iterator and Enumeration, it is recommended that they are placed in the context only when it cannot be avoided, and you should let Velocity find the appropriate reusable iterative interface when that is sufficient and possible.

IteratorEnumeration については、 どうしても必要な時のみコンテキストに設定することをお勧めします。 それが可能で問題がないのなら、再利用可能な繰り返しインタフェースを Velocity が見つけるという形にすべきです。

There are good reasons to use the java.util.Iterator interface directly (large data sets via JDBC, for example), but if it can be avoided, it might be better to use something else. By 'directly' , we meant doing something like:

直接 java.util.Iterator インタフェースを使用するのが適切な場合もあります (例えば、JDBC 経由の大きなデータセット)。しかし、もし避けられるのであれば、 他のものを使う方がよいでしょう。「直接」とは以下のようなやり方のことです。

Vector v = new Vector();
v.addElement("Hello");
v.addElement("There");

context.put("words", v.iterator() );

where the Iterator itself is placed into the context. Instead, if you simply did:

この場合、Iterator そのものがコンテキストに設定されます。 代わりに単純に以下のようにしたとしましょう。

context.put("words", v );

then all would be fine: Velocity would figure out that Vector implement Collection (via List), and therefore will find the iterator() method, and use that to get a 'fresh' Iterator for its use each time it needs to. With just a plain Iterator (the first snippet above...), once velocity has used it in a #foreach(), Velocity has no way of getting a new one to use for the next #foreach() it is used in. The result is no output from any subsequent #foreach() blocks using that reference.

これですべて丸く収まります。Velocity は Vector が (List 経由で) Collection を実装していることを理解するので、iterator() メソッドを見つけられますし、このメソッドを使って、必要に応じて毎回「新鮮な」 Iterator を取得します。Iterator をそのまま使った場合(二つのコード例の最初の方)、 Velocityが #foreach() で一度使うと、次の #foreach() で使う場合に、新しいオブジェクトを取得できません。その結果、 このリファレンスを使った2回目以降の #foreach() ブロックは何も出力できません。

This above isn't meant to give the impression that iterating over collections in Velocity is something that requires great care and thought. Rather, the opposite is true, in general. Just be careful when you place an Iterator into the context.

以上の説明で、Velocity ではコレクションを使った繰り返し処理は、 慎重によく考えて行なう必要があると言いたいわけではありません。 むしろ通常は逆なのです。コンテキストに Iterator [訳注:Enumerationも同様です] を設定する時だけ気をつければいいのです。

Context Chaining コンテキスト連鎖

An innovative feature of Velocity's context design is the concept of context chaining. Also sometimes referred to as context wrapping, this advanced feature allows you to connect separate contexts together in a manner that makes it appear as one 'contiguous' context to the template.

Velocity のコンテキスト設計の画期的な機能として、コンテキスト連鎖 という概念があります。時には コンテキストラッピング と呼ばれることもある、 この先進的な機能を使うと、別々のコンテキストをくっつけて、テンプレートからは、 「連続した」コンテキストであるように見えるようにできます。

This is best illustrated by an example :

具体的に例を示すのが一番でしょう。

VelocityContext context1 = new VelocityContext();

context1.put("name","Velocity");
context1.put("project", "Jakarta");
context1.put("duplicate", "I am in context1");

VelocityContext context2 = new VelocityContext( context1 );

context2.put("lang", "Java" );
context2.put("duplicate", "I am in context2");

template.merge( context2, writer );

In the code above, we have set up context2 such that it chains context1. This means that in the template, you can access any of the items that were put into either of the two VelocityContext objects, as long as there is no duplication of the keys used to add objects. If that is the case, as it is above for the key 'duplicate', the object stored in the nearest context in the chain will be available. In this example above, the object returned would be the string "I am in context2".

上記のコードでは、 context2 が context1 に連鎖するように context2 を設定しました。 つまり、テンプレートでは二つの VelocityContext オブジェクトのどちらに設定した項目でも、 オブジェクト追加時に使ったキーが重複しない限りはアクセスできるということです。 上記の「duplicate」というキーのように、重複している場合は、 連鎖の後方のコンテキストに格納されたオブジェクトが利用できます。 上記の例でいえば、オブジェクトとして返されるのは、 「I am in context2」という文字列となります。

Note that this duplication, or 'covering', of a context item does not in any way harm or alter the covered object. So in the example above, the string "I am in context1" is alive and well, still accessable via context1.get("duplicate"). But in the example above, the value of the reference '$duplicate' in the template would be 'I am in context2', and the template has no access to the covered string 'I am in context1'.

このような、コンテキストの項目の重複または「被覆」 (covering) によって、 覆われたオブジェクトに害が及んだり変更されたりはしないことに注意して下さい。 したがって上記の例では、「I am in context1」は無事ですし、context1.get("duplicate") でアクセスできます。しかし、テンプレート内では「$duplicate」というリファレンスの値は 「I am in context2」となり、覆われた「I am in context1」という文字列に、 テンプレートはアクセスできません。

Note also that you have to be careful when you are relying on the template to add information to a context that you will examine later after the rendering. The changes to the context via #set() statements in a template will affect only the outer context. So make sure that you don't discard the outer context, expecting the data from the template to have been placed onto the inner one.

同様に、テンプレート処理をした後で検証するコンテキストに、 情報を追加するテンプレートを使っている場合は注意が必要です。テンプレート内の #set() ステートメント経由でコンテキストに変更を加えても、 外側の [訳注:連鎖の後方の] コンテキストにしか影響しません。したがって、 テンプレートからのデータが内部のコンテキストに設定されていると思って、 外側のコンテキストを廃棄したりしないように気をつけてください。

This feature has many uses, the most common so far is providing layered data access and toolsets.

この機能はいろんな使い方ができますが、その中でも特に一般的なのは、 階層化したデータアクセスやツールセットの提供でしょう。

As mentioned before, the Velocity context mechanism is also extendable, but beyond the current scope of this guide. If you are interested, please see the classes in the package org.apache.velocity.context to see how the provided contexts are put together. Futher, there are a few examples in the examples/context_example directory in the distribution which show alternate implementations, including [a goofy] one that uses a database as the backing storage.

先に述べたとおり、Velocity コンテキストの仕組も拡張できるのですが、それについては、 今のところ、このガイドの範囲外です。もし興味があるのでしたら、コンテキストがどのように まとめられるかを理解するために org.apache.velocity.context パッケージの各クラスのソースコードをご覧下さい。さらに、配布の examples/context_example ディレクトリにあるいくつかのサンプルでは、 代替的な実装を示しており、その中にはバックアップ先としてデータベースを使う 「あまり賢くない」 サンプルもあります。 [訳注:context_exampleのことだと思われます。]

Please note that these examples are unsupported and are there for demonstration/educational purposes only.

これらのサンプルはあくまでデモや教育のためのものであり、サポートはされませんので、 ご注意ください。

Objects Created in the Template テンプレートで生成されたオブジェクト

There are two common situations where the Java code must deal with objects created at runtime in the template :

テンプレート内で実行時に生成されたオブジェクトを Java コードが扱わざるを得ない 状況としてよくあるのは次の2種類でしょう。

When a template author calls a method of an object placed into the context by Java code.

テンプレート作者が Java コードがコンテキストに設定したオブジェクトのメソッドを 呼び出すとき。

#set($myarr = ["a","b","c"] )
$foo.bar( $myarr )

When a template adds objects to the context, the Java code can access those objects after the merge process is complete.

テンプレートでオブジェクトをコンテキストに加えるとき。この場合、 マージ処理が完了した後で、Java コードはこれらのオブジェクトにアクセスできます。

#set($myarr = ["a","b","c"] )
#set( $foo = 1 )
#set( $bar = "bar")

Dealing with these cases if very straighforward, as there are just a few things to know:

こういうケースを扱う場合、とても単純な場合でも、以下の事柄だけは知っておくべきです。

  • The VTL RangeOperator [ 1..10 ] and ObjectArray ["a","b"] are java.util.ArrayList objects when placed in the context or passed to methods. Therefore, your methods that are designed to accept arrays created in the template should be written with this in mind.
  • Numbers will be Integers in the context, and strings will be, of course, Strings.
  • Velocity will properly 'narrow' args to method calls, so calling setFoo( int i ) with an int placed into the context via #set() will work fine.
  • VTLのRangeOperator [ 1..10 ] や ObjectArray ["a","b"] は、 コンテキストに設定される場合や、メソッドに渡される場合は、 java.util.ArrayList オブジェクトとなります。したがって、 テンプレート内で生成された配列を受け取るメソッドを作成する時は、 このことを考慮する必要があります。
  • コンテキスト内では数字は Integer になり、文字列はもちろん String になります。
  • Velocityはメソッド呼び出しにおいて引数を適切に「狭く」[キャスト]します。 したがって、 #set() を通してコンテキストに設定された int データを引数に setFoo( int i ) を呼び出しても正しく動作します。
Other Context Issues その他のコンテキストの課題

One of the features provided by the VelocityContext (or any Context derived from AbstractContext) is node specific introspection caching. Generally, you as a the developer don't need to worry about this when using the VelocityContext as your context. However, there is currently one known usage pattern where you must be aware of this feature.

VelocityContext(および AbstractContext から派生するすべてのコンテキスト)で提供される 機能の1つに、ノード単位イントロスペクションキャッシングがあります。通常の場合、 開発者であっても、 VelocityContext をコンテキストとして使う限りは、 この機能を気にする必要はありません。しかし、この機能を意識しなければならない 既知の使い方のパターンが現在一つだけあります。

The VelocityContext will accumulate intropection information about the syntax nodes in a template as it visits those nodes. So, in the following situation:

VelocityContext ではテンプレート内の構文ノードに関する、 イントロスペクション情報を、ノードを処理する(訪れる)ごとに蓄積していきます。 したがって、

  • You are iterating over the same template using the same VelocityContext object.
  • Template caching is off.
  • You request the Template from getTemplate() on each iteration.
  • 同じ VelocityContext を使って、同じテンプレート上で繰り返し処理を行っている
  • Template キャッシュがオフである
  • 繰り返しごとに getTemplate() で Template を要求している

It is possible that your VelocityContext will appear to 'leak' memory (it is really just gathering more introspection information.) What happens is that it accumulates template node introspection information for each template it visits, and as template caching is off, it appears to the VelocityContext that it is visiting a new template each time. Hence it gathers more introspection information and grows. It is highly recommended that you do one or more of the following :

という条件が重なると、VelocityContext が「メモリリーク」しているように見える ことがあります(実際には、さらなるイントロスペクション情報を集めているだけです)。 この場合、処理する(訪れる)テンプレートごとに、テンプレートノードのイントロスペクション 情報が蓄積され、テンプレートのキャッシュがオフであるため、 VelocityContext は、 毎回新しいテンプレートを処理していると思ってしまいます。そのため、他の場合に比べて、 より多くのイントロスペクション情報を集めることになり、消費メモリが多くなるのです。 この場合、以下の対応のうち最低でも一つは行なうことを強く推奨します。

  • Create a new VelocityContext for each excursion down through the template render process. This will prevent the accumulation of introspection cache data. For the case where you want to reuse the VelocityContext because it's populated with data or objects, you can simply wrap the populated VelocityContext in another, and the 'outer' one will accumulate the introspection information, which you will just discard. Ex. VelocityContext useThis = new VelocityContext( populatedVC ); This works because the outer context will store the introspection cache data, and get any requested data from the inner context (as it is empty.) Be careful though - if your template places data into the context and it's expected that it will be used in the subsequent iterations, you will need to do one of the other fixes, as any template #set() statements will be stored in the outermost context. See the discussion in Context chaining for more information.
  • Turn on template caching. This will prevent the template from being re-parsed on each iteration, resulting the the VelocityContext being able to not only avoid adding to the introspection cache information, but be able to use it resulting in a performance improvement.
  • Reuse the Template object for the duration of the loop iterations. Then you won't be forcing Velocity, if the cache is turned off, to reread and reparse the same template over and over, so the VelocityContext won't gather new introspection information each time.
  • テンプレート処理プロセスによる解析毎に新しい VelocityContext を生成します。 これにより、イントロスペクションキャッシュデータの蓄積を防ぐことができます。 データやオブジェクトをロードしているという理由で VelocityContext を再利用したいのなら、単にロードした VelocityContext をラップ[連鎖]すればいいのです。そうすれば「外側の」コンテキストが イントロスペクション情報を蓄積するので、あとはそれを廃棄するだけです。 例) VelocityContext useThis = new VelocityContext( populatedVC ); これで問題ないのは、 外側のコンテキストはイントロスペクションのキャッシュデータを保存しつつ、 要求されたデータは全て、(キャッシュされない) 内側のコンテキストから取得するからです。 ただし気をつけるべきことがあります ─ テンプレートでコンテキストにデータを設定し、 次の繰り返しでそれが使われることがわかっている場合は、 他の対応策を取る必要があります。 なぜなら、テンプレートで #set() メソッドを使う場合、 一番外側のコンテキストに保存されてしまうからです。詳しくは、 コンテキスト連鎖 の説明をご覧下さい。
  • テンプレートキャッシュをオンにします。これにより、繰り返しのたびにテンプレートが 解析されることが防げるため、イントロスペクションのキャッシュ情報の追加が避けられる のみならず、キャッシュ情報を使うことで性能向上につながります。
  • ループによる繰り返しの間はテンプレートオブジェクトを再利用します。そうすれば、 キャッシュがオフであっても、 Velocity は同じテンプレートを何度も読み込んだり、 何度も解析したりしなくなるので、 VelocityContext は毎回新しいイントロスペクション 情報を集めなくなります。


Using Velocity In Servlets − サーブレットでVelocityを使う
Servlet Programming サーブレットのプログラミング

The most common use of Velocity is in the area of Java Servlet programming for the WWW. There are many reasons why Velocity is well suited for this task, one of the primary ones is Velocity's enforcement of the separation of the presentation (or view) layer from the code layer. There are many resources on this subject, including this.

Velocity の最も代表的な利用領域は WWW 向けの Java サーブレットプログラミングの領域です。 Velocity がこの領域で最適な理由はたくさんありますが、主要な理由のひとつに、 Velocity ではコード層からプレゼンテーション層(またはビュー) を強制的に分離できることが挙げられます。 このことに関しては多くのリソースがありますが、例えば こういうものがあります。

The basic technique of using Velocity in a servlet environment is very simple. In a nutshell, all you must do is extend the provided VelocityServlet base class and implement a single method, handleRequest(). That's really all that is required to use Velocity in your servlet development.

サーブレット環境で Velocity を使う基本テクニックは、非常に単純なものです。 念のために説明すると、やるべきことは提供されている VelocityServlet 基本クラスを 拡張して、ひとつのメソッド(handleRequest())を実装するだけです。 サーブレット開発で Velocity を使うのに必要なのは本当にこれだけなのです。

As of Velocity 1.1, there are two handleRequest() methods :

public Template handleRequest( Context )

This is the older of the two methods. This method requires that you return a valid Template object. If not valid, or null, this is considered an error condition, and will result in the error() error handling method being called. You may override the error() if you wish. If returning a null is something you expect to do (for example, you will want to redirect requests) it is recommended that you use the newer method, listed next.

public Template handleRequest( HttpServletRequest, HttpServletResponse, Context )
This is the newer of the two handleRequest() methods, implemented in version 1.1. The difference with this method is that the HttpServletRequest and HttpServletResponse objects are passed to you as arguments to the method, as well as in the Context. The other difference is that this method can return null to indicate that all processing has been handled by the method, and that Velocity should do nothing further than call requestCleanup(). This is extremely useful is you wish to redirect the request, for example.
As always, please refer to the Javadoc API documentation for the definitive and latest notes.

Velocity 1.1 では、以下の2つの handleRequest() メソッドがあります。

public Template handleRequest( Context )

これは、2つのメソッドの古い方です。このメソッドでは有効なテンプレートオブジェクトを 返す必要があります。有効でなかったり、null だったりすると、 エラーと見なされ、その結果、 error() エラーハンドリングメソッドが呼び出されます。必要なら error() をオーバーライドできます。null を返す可能性がある場合 (例えば、リクエストをリダイレクトさせたい場合)は、 次に説明する新しいメソッドを使用することが推奨されます。
public Template handleRequest( HttpServletRequest, HttpServletResponse, Context )
これは2つの handleRequest() メソッドの新しい方で、バージョン 1.1 において実装されました。上のメソッドとの違いは、このメソッドでは、Context に加えて、 HttpServletRequestHttpServletResponse オブジェクトがメソッドに対する引数として渡されるということです。もう一つの違いは、 このメソッドでは全ての処理をメソッドが行ったことを明示するために null を返すことができることです。この場合 Velocity は requestCleanup() 以外は何もしません。これは、例えば要求をリダイレクトしたい場合に極めて便利です。
当然のことながら、最も確実で最新の注意事項については、Javadoc API ドキュメンテーションを参照してください。

The following code is similar to the SampleServlet.java class included in the distribution in the examples directory.

以下のコードは、配布のサンプルディレクトリに入っている SampleServlet.java クラスと 同じ物です。

public class SampleServlet extends VelocityServlet
{
    public Template handleRequest( HttpServletRequest request,
                                   HttpServletResponse response,
                                   Context context )
    {

        String p1 = "Jakarta";
        String p2 = "Velocity";

        Vector vec = new Vector();
        vec.addElement( p1 );
        vec.addElement( p2 );

        context.put("list", vec );

        Template template = null;

        try
        {
            template =  getTemplate("sample.vm");
        }
        catch( ResourceNotFoundException rnfe )
        {
          // couldn't find the template
        }
        catch( ParseErrorException pee )
        {
          // syntax error : problem parsing the template
        }
        catch( Exception e )
        {}

        return template;
    }
}
public class SampleServlet extends VelocityServlet
{
    public Template handleRequest( HttpServletRequest request, 
                                   HttpServletResponse response, 
                                   Context context )
    {

        String p1 = "Jakarta";
        String p2 = "Velocity";

        Vector vec = new Vector();
        vec.addElement( p1 );
        vec.addElement( p2 );

        context.put("list", vec );

        Template template = null;

        try
        {
            template =  getTemplate("sample.vm");
        }
        catch( ResourceNotFoundException rnfe )
        {
          // テンプレートを見つけられなかった
        } 
        catch( ParseErrorException pee )
        {
          // 構文エラー:テンプレート解析で問題あり
        }
        catch( Exception e )
        {}

        return template;
    }
}

Look familiar? With the exception of creating the context object, which is done for you by the VelocityServlet base class, and the merge() step which is also done for you by the VelocityServlet base class, it's identical to the basic code pattern we mentioned at the beginning of this guide. We take the context, add our application data, and return a template.

見覚えがありませんか? VelocityServlet 基本クラスが代わりに行なう、 コンテキストオブジェクトの生成と merge() ステップを除いて、 このガイドの初めの方に説明した基本的なコードパターンと同じです。 この場合は、コンテキストを取得し、アプリケーションデータを追加し、 テンプレートを返します。

The default Context object that is passed into the handleRequest() methods contains both the current HttpServletRequest and HttpServletResponse objects. They are placed in the context using the the constants VelocityServlet.REQUEST (value = 'req') and VelocityServlet.RESPONSE (value = 'res') respectively. To access and use these objects in your Java code :

handleRequest()メソッドに渡されるデフォルトの Context オブジェクトには、現在のHttpServletRequestHttpServletResponseオブジェクトの両方が含まれています。 これらは、定数 VelocityServlet.REQUEST (値は「req」) と VelocityServlet.RESPONSE (値は「res」) を使って、 コンテキストに設定されます。Java コードでこれらのオブジェクトにアクセスするには、 以下のようにします。

public Template handleRequest(  Context context )
{
    HttpServletRequest request =  (HttpServletRequest) context.get( REQUEST );
    HttpServletResponse response =  (HttpServletResponse) context.get( RESPONSE );

   ...

and in your templates:

そしてテンプレートでは以下のようにアクセスします。

#set($name = $req.getParameter('name') )

For more advanced uses, the VelocityServlet base class allows you to override parts of the handling of the request processing. The following methods may be overridden :

Properties loadConfiguration( ServletConfig )

Allows you to override the normal configuration mechanism and add or alter the configuation properties. This is useful for overriding or augmenting template and log paths, to set the absolute path into the webapp root at runtime.
Context createContext(HttpServletRequest, HttpServletResponse )
Allows you to create the Context object yourself. This allows more advanced techniques, such as chaining or pre-loading with tools or data. The default implementation simply returns a VelocityContext object with the request and response objects placed inside. The request and response objects are wrapped in simple wrapper classes to avoid introspection problems that may occurr in some servlet container implementations. You can use the request and repsponse objects normally, accessing methods of either from the template. Just note that they aren't specifically javax.servlet.XXXX classes, if that is important to you.
void setContentType( HttpServletRequest,HttpServletResponse )
Allows you to examine the request and set the content type yourself, depending on the request or client. The default implementation sets the content type to be that either specified in the velocity.properties, if any, or the default, "text/html" if not specified in the properties.
void mergeTemplate( Template, Context, HttpServletResponse )
Allows you to produce the output stream. The VelocityServlet uses a pool of very efficient Writer classes, so this would usually be overridden in special situations.
void requestCleanup( HttpServletRequest, HttpServletResponse , Context )
Allows you to do any cleanup or resource reclamation at the end of the request processing. The default does nothing.
protected void error( HttpServletRequest, HttpServletResponse, Exception )
Error handler that is called an exception occurrs in request processing. Default implementation will send a simple HTML message with stacktrace and exception information back to the user. Override for custom client messages and more advanced problem handling.
For further information, please see the Javadoc API documentation.

より高度な使い方として、 VelocityServlet 基本クラスは、 リクエスト処理のハンドリングの一部をオーバーライドできます。 オーバーライドできるのは以下の各メソッドです。

Properties loadConfiguration( ServletConfig )

通常の設定メカニズムをオーバーライドし、設定プロパティの追加や変更ができます。 実行時に Webアプリケーションのルートに絶対パスを設定するために、 テンプレートやログのパスをオーバーライドしたり増やしたりするのに役立ちます。
Context createContext(HttpServletRequest, HttpServletResponse )
自分でコンテキストオブジェクトを生成できます。これによってより高度なテクニック、 例えば、例えばコンテキストの連鎖や、ツールやデータでの事前ロードを行なえます。 デフォルトの実装では、内部で設定されたリクエストおよびレスポンスオブジェクトを 含む VelocityContext オブジェクトを返します。 リクエストおよびレスポンスオブジェクトは、サーブレットコンテナの実装によっては発生する かもしれない、イントロスペクションでの問題を回避するために単純なラッパクラスで ラップされています。リクエストおよびレスポンスオブジェクトは通常どおり使用できますし、 テンプレートからもどちらのメソッドにもアクセスできます。 人によっては重要かも知れないので、念のため注記しておくと、これらのクラスは、 厳密には javax.servlet.XXXX クラスではありません。
void setContentType( HttpServletRequest,HttpServletResponse )
リクエストをチェックして、リクエストやクライアントに応じて独自のコンテントタイプを 設定できます。デフォルトの実装ではコンテントタイプは velocity.properties に指定した値か、指定されていなければデフォルトで「text/html」が設定されます。
void mergeTemplate( Template, Context, HttpServletResponse )
出力ストリームを生成できます。 VelocityServlet は非常に効率的な Writer クラスのプールを使いますので、通常は特別な状況においてのみオーバーライドされます。
void requestCleanup( HttpServletRequest, HttpServletResponse , Context )
リクエスト処理の最後に、クリーンアップやリソース再利用といった処理ができます。 デフォルトでは、何もしません。
protected void error( HttpServletRequest, HttpServletResponse, Exception )
リクエスト処理での例外発生時に呼ばれるエラーハンドラ。 デフォルトの実装では、スタックトレースと例外情報とともに単純な HTML メッセージをユーザに送ります。クライアントメッセージをカスタマイズしたり、 より高度にエラーを扱うためにオーバーライドします。
詳細情報は、Javadoc の API ドキュメント をご覧下さい。

Deployment 配備

When you deploy your Velocity-based servlets, you will certainly want to ensure that your properties file is used to configure the Velocity runtime. Under Tomcat, one way to accomplish this is by placing your velocity.properties file into the root directory of your web app (webapps/appname ) and then add the following to your WEB-INF/web.xml file :

Velocity ベースのサーブレットを配備する場合、プロパティファイルが Velocity ランタイムを設定するのに使われているかどうか確認したいことがあるかと思います。 Tomcat でこの目的を達成するためには、Web アプリケーションのルートディレクトリ(webapps/appname) に velocity.properties ファイルを置き、以下の内容を WEB-INF/web.xml ファイルに追加するという方法があります。

<servlet>
  <servlet-name>MyServlet</servlet-name>
  <servlet-class>com.foo.bar.MyServlet</servlet-class>
  <init-param>
      <param-name>properties</param-name>
      <param-value>/velocity.properties</param-value>
  </init-param>
</servlet>

Assuming all is right, this will ensure that when MyServlet is loaded, it will use the velocity.properties file to initialize itself rather than relying on it's internal defaults.

記述が全て正しければ、MyServlet がロードされるとき、内部のデフォルトに依存せずに、 MyServlet自身を初期化するために velocity.properties ファイルを確実に使用します。

Note that Velocity uses a singleton model for it's central core Runtime class, so it is a very good idea to put the velocity-XX.jar into the WEB-INF/lib directory in all web applications that use Velocity to ensure that the web app classloader is managing your Runtime instance, rather than putting it in the CLASSPATH or the top level lib directory of the servlet runner.

注意: Velocity は中心となるコアの Runtime クラスで Singleton モデルを使うので、 確実に Web アプリのクラスローダが自分の Runtime インスタンスを管理できるように、 velocity-XX.jar は CLASSPATH やサーブレットコンテナのトップレベルの lib ディレクトリに置くのではなく、Velocity を使用するすべての Web アプリケーションの WEB-INF/lib ディレクトリに置くのがよいでしょう。

This deployment method will ensure that different web applications will not be subject to Velocity configuration conflicts.

この配備方法なら、異なる Web アプリケーションでの Velocity 設定での衝突を確実に防げます。