|
Velocityについて
コミュニティ
ドキュメント
ツール
比較
日本語訳について
|
|
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.
-
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.
-
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.
-
Go to the
build directory in the distribution.
-
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.
-
While not required, testing the build is a good idea. Use the
test target mentioned above.
-
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)
-
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 配布のルートディレクトリを基準にしていますのでご注意ください。
-
Velocity 配布を入手します。
リリース版や、夜間スナップショットとしても入手できますし、直接
CVS コードリポジトリからも入手可能です。
どれでも構いませんが、最新の機能なら、夜間スナップショットがおそらく一番良いでしょう。
詳細情報は、こちらを参照してください。
-
Java 構築ツールの
Jakarta Ant を
まだインストールしていない場合には、まずそれをインストールしてください。
Velocity を使用するには必要ありませんが、Velocity を構築するのに必要です。
-
配布の
build ディレクトリに移動します。
-
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 利用できる構築ターゲットの一覧を表示します。
-
ビルドのテストは必要ではありませんが、するに越したことはないでしょう。
上記の
test ターゲットを使ってください。
-
これで、 Velocity を、使用する準備ができました。JAR ファイルを、
クラスパスなどの適切な場所(サーブレットで使うのなら、
Webアプリケーションの lib ディレクトリとか)に置きます
-
サンプルを試してみたいという場合(はじめての場合には特に推奨します)には、
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 に入っています。
しかし、デフォルトのビルドターゲット(上述)には入っていません。
デフォルトのビルドターゲットを使う場合は、
クラスパスにこの依存関係を加えなければなりません。
|
|
|
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 を使う場合
(実際のところ、どこで使う場合も)、通常は以下のことを行なう必要があります。
- 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.
- Create a Context object (more on what that is later).
- Add your data objects to the Context.
- Choose a template.
- 'Merge' the template and your data to produce the ouput.
- Velocity を初期化します。
これは、Singleton と、「分離実行時インスタンス」(詳細については下記参照)
という Velocity の利用パターンの両方に適用され、一度だけ行なう必要があります。
- Context オブジェクトを生成します (詳細は後述)。
- データオブジェクトを Context に追加します。
- テンプレートを選択します。
- 出力を生成するためにデータとテンプレートを「マージ」します。
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 パッケージの
Runtime、RuntimeConstants、RuntimeSingleton、
RuntimeInstance の各クラスは絶対に使わないでください。
これらは内部使用のみを想定しており、いつか変更される可能性があります。
上で説明したとおり、使うべきクラスは 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.
Iterator と Enumeration については、
どうしても必要な時のみコンテキストに設定することをお勧めします。
それが可能で問題がないのなら、再利用可能な繰り返しインタフェースを
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
に加えて、 HttpServletRequest と HttpServletResponse
オブジェクトがメソッドに対する引数として渡されるということです。もう一つの違いは、
このメソッドでは全ての処理をメソッドが行ったことを明示するために
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
オブジェクトには、現在のHttpServletRequest と
HttpServletResponseオブジェクトの両方が含まれています。
これらは、定数 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
設定での衝突を確実に防げます。
|
|
|
Using Velocity In General Applications − 一般的なアプリケーションで Velocity を使う
|
As Velocity was designed to be a general-use tool, it is just as useful in
general application programs as it is servlets. In general, you can use the
same programming pattern discussed at the beginning of this guide, but there
are a few utility methods provided for application use, just like we provide
the VelocityServlet base class for ease of use in servlet programming.
The only new responsibility you have as the application programmer is to
initialize the Velocity runtime engine, but that is easy.
Velocity は汎用ツールとして設計されたので、一般的なアプリケーションプログラムでも、
サーブレットで使う場合と同様に役に立ちます。
通常はこのガイドの初めに説明したのと同じプログラミングパターンを使うことができますが、
サーブレットプログラミングで簡単に使える VelocityServlet 基本クラスを提供したのと同様に、アプリケーション用に、いくつかのユーティリティメソッドが用意されています。
アプリケーションプログラマとして追加で行なう必要があるのは Velocity
ランタイムエンジンを初期化することだけで、しかもそれは簡単です。
The Velocity Helper Class
Velocity ヘルパクラス
Velocity contains an application utility class called Velocity
( org.apache.velocity.app.Velocity ). The purpose of this class
is to provide the necessary methods required to initialize Velocity, as well as
useful utility routines to make life easier in using Velocity. This class is
documented in the project's javadoc, so please look there for definitive
details. This documentation is intended to be of a tutorial nature; therefore
for compete API information, the Javadoc is the definitive source.
Velocity には、Velocity(org.apache.velocity.app.Velocity)
と呼ばれるアプリケーションユーティリティクラスがあります。
このクラスの目的は、Velocity の初期化で必要なメソッドや Velocity
を使いやすくするのに役に立つユーティリティルーチンを提供することです。
このクラスはプロジェクトの Javadoc で文書化されていますので、より確実な詳細については、
そちらを参照してください。このドキュメンテーションは、本来チュートリアルであるため、
完璧な API 情報については、Javadoc が最も信頼できる情報源です。
The Velocity runtime engine is a singleton instance that provides resource,
logging and other services to all Velocity users running in the same JVM.
Therefore, the runtime engine is initialized only once. You can attempt to
initialize Velocity more than once, but only the first initialization will
apply. The rest of the attempts will be ignored. The Velocity utility
class currently provides five methods used in configuration of the runtime engine.
Velocity ランタイムエンジンは、同じ JVM で実行される全ての Velocity
ユーザに対してリソース、ロギングなどのサービスを提供する Singleton インスタンスです。
したがって、ランタイムエンジンは一度だけ初期化されます。Velocity
の初期化は何度でも試せますが、適用されるのは最初の初期化のみで、他のものは無視されます。
Velocity ユーティリティクラスは、現在ランタイムエンジンの設定で使用される
5つのメソッドを提供します。
The five configuration methods are :
設定メソッドは以下の通りです。
setProperty( String key, Object o )
Sets the property key with the value o. The value
is typically a String, but in special cases can also be a comma-separated
list of values (in a single String, ex."foo, bar, woogie") as well as other
things that will arise.
Object getProperty( String key )
Returns the value of the property key. Note that you must be aware of the
type of the return value, as they can be things other than Strings.
init()
Initializes the runtime with the default properties provided in the
distribution.(These are listed below in the section pertaining to
properties.)
init( Properties p ) Initialize the runtime with the
properties contained in the java.util.Properties object passed
as an argument.
init( String filename ) initilizes the runtime
using the properties found in the properties file filename
setProperty( String key, Object o )
プロパティ key に値 o を設定します。
値は通常は String ですが、特殊なケースとして、
値のコンマ区切りのリスト ("foo, bar, woogie" といった
String) の可能性もありますし、他のケースも将来出てくるかもしれません。
Object getProperty( String key )
プロパティキーの値を返します。
注意: String 以外もありうるので、あなたは戻り値のタイプを
把握していなければなりません。
init()
配布で提供されるデフォルトの各プロパティでランタイムを初期化します。
(プロパティに関するセクション (後述)
にデフォルト値の一覧があります。)
init( Properties p )
引数として渡される java.util.Properties
オブジェクトに含まれる各プロパティでランタイムを初期化します。
init( String filename )
filename で示されるプロパティファイルにある各プロパティでランタイムを初期化します。
Note that in each case, the default properties will be used as a base
configuration, and any additional properties specified by the application
will replace individual defaults. Any default properties not overwritten
will remain in effect. This has the benefit that only the properties
you are interested in changing need to be specified, rather
than a complete set.
注意: それぞれの場合、デフォルトプロパティは、基本設定として使用され、
アプリケーションで指定された追加のプロパティはデフォルトのプロパティを上書きします。
オーバーライトされないデフォルトプロパティは全て有効となります。この方法には、
プロパティ全てでなく変更したい部分だけ指定できるという利点があります。
Another thing to note is that the init() calls may be called
more than once without harm in an application. However, the first call to any
of the init() functions will configure the engine with the
configuration properties set at that point, and any further configuration
changes or init() calls will be ignored.
もう一点、注意事項として、 init() の呼び出しは、
アプリケーションに悪影響を与えずに複数回行われるかもしれません。
しかし、エンジンの設定は、最初のinit() メソッドの呼び出しで
セットされた設定プロパティによって行われ、
それ以降の設定変更や init() 呼び出しは無視されます。
The most common approaches to initializing Velocity will be something like :
最も一般的な Velocity の初期化の方法は以下の通りです。
- Setup the configuration values you wish to set in a file in the same
format as org/apache/velocity/runtime/defaults/velocity.properties
(the default set), or in a
java.util.Properties, and then
call either init( filename ) or init( Properties )
- Set the configuration values individually using
setProperty()
and then call init(). This method is generally used by more advanced
applications that already have their own configuration management system -
this allows the application so configure Velocity based upon values it generates
at runtime, for example.
-
設定したい値を org/apache/velocity/runtime/defaults/velocity.properties(デフォルトのセット)と同じフォーマットのファイル、または
java.util.Properties
で設定し、その上で init( filename ) または
init( Properties ) を呼び出します。
-
setProperty() を使って設定値を別々にセットし、それからinit()
を呼びます。この方法は通常、すでに設定管理システムを持つ、
より高度なアプリケーションで使われます ─ この方法を使えば、
例えば実行時に生成する値に基づいてアプリケーションで Velocity
を設定できます。
Once the runtime is initialized, you can do with it what you wish.. This mostly
revolves around rendering templates into an output stream, and the Velocity
utility class allows you to do this easily. Currently, here are the methods
and a brief description of what they do :
一度ランタイムが初期化されたら、ランタイムでやりたいことができます。
その際に行なうことのほとんどは、テンプレートを処理して出力ストリームに送ることであり、
Velocity ユーティリティクラスで簡単に行なうことができます。
現状でのメソッドと処理概要の一覧は以下の通りです。
-
evaluate( Context context, Writer out, String logTag,
String instring )
evaluate( Context context, Writer writer, String logTag,
InputStream instream )
These methods will render the input, in either the form of String or
InputStream to an output Writer, using a Context that you provide.
This is a very convenienient method to use for token replacement of
strings, or if you keep 'templates' of VTL-containing content in a
place like a database or other non-file storage, or simply generate such
dynamically.
-
invokeVelocimacro( String vmName, String namespace, String params[],
Context context, Writer writer )
Allows direct access to Velocimacros. This can also be accomplished
via the evaluate() method above if you wish. Here you
simply name the vm you wish to be called, create an array of args to the VM,
a Context of data, and Writer for the output. Note that the VM args
must be the 'keys' of the data objects in the Context, rather than
literal data to be used as the arg. This will probably change.
-
mergeTemplate( String templateName, Context context, Writer writer )
Convenient access to the normal template handling and rendering services
of Velocity. This method will take care of getting and rendering the
template. It will take advantage of loading the template according
to the properties setting for the file resource loader, and therefore
provides the advantage of file and parsed template caching that Velocity
offers. This is the most efficient way to access templates,
and is recommended unless you have special needs.
-
boolean templateExists( String name )
Determines if a template name is able to be found by
the currently configured resource loaders.
-
evaluate( Context context, Writer out, String logTag,
String instring )
evaluate( Context context, Writer writer, String logTag,
InputStream instream )
この2つのメソッドは、String あるいは InputStream 形式の入力を、
指定した Context を使って処理し、出力 Writer に送ります。
文字列のトークンの置換に使うとか、データベースなどファイルでないストレージに VTL
を含んだ内容の「テンプレート」を保持したり同様のデータを動的に作成したりする場合に、
非常に便利なメソッドです。
-
invokeVelocimacro( String vmName, String namespace, String params[],
Context context, Writer writer )
Velocimacro (VM) に直接アクセスできます。やろうと思えば、上記の
evaluate() メソッドでも行なえます。このメソッドの場合は、
VMに好きな名前をつけ、VMへの引数となる配列やデータのコンテキスト、
それに出力先のWriterを生成します。注意: VM の引数は、
引数として使う文字列データではなく、Context 内のデータオブジェクトの「キー」
でなければなりません。これは将来変更される可能性があります。
-
mergeTemplate( String templateName, Context context, Writer writer )
Velocity の通常のテンプレート処理サービスに簡単にアクセスできます。このメソッドは、
テンプレートの取得と処理を担当します。このメソッドには、ファイルリソースローダ向けの
プロパティ設定にしたがってテンプレートをロードできるという利点があり、それによって
Velocity が提供するファイルテンプレートおよび解析済みテンプレートのキャッシュ化という
利点が得られます。この方法はテンプレートにアクセスするのに最も効率的な方法であり、
特に必要がない限りはこの方法をお勧めします。
-
boolean templateExists( String name )
name で指定されたテンプレートが現在設定されているリソースローダで
見つけられるかどうか判定します。
Once we know about these basic helpers, it is easy to write Java program
that uses Velocity. Here it is:
一度これらの基本ヘルパを理解すれば、Velocity を使った Java
プログラムを書くのは簡単です。
こんな感じです。
 |
 |
 |
 |
import java.io.StringWriter;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.VelocityContext;
public class Example2
{
public static void main( String args[] )
{
/* first, we init the runtime engine. Defaults are fine. */
Velocity.init();
/* lets make a Context and put data into it */
VelocityContext context = new VelocityContext();
context.put("name", "Velocity");
context.put("project", "Jakarta");
/* lets render a template */
StringWriter w = new StringWriter();
Velocity.mergeTemplate("testtemplate.vm", context, w );
System.out.println(" template : " + w );
/* lets make our own string to render */
String s = "We are using $project $name to render this.";
w = new StringWriter();
Velocity.evaluate( context, w, "mystring", s );
System.out.println(" string : " + w );
}
}
|
 |
 |
 |
 |
 |
 |
 |
 |
import java.io.StringWriter;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.VelocityContext;
public class Example2
{
public static void main( String args[] )
{
/* まず実行時エンジンを初期化する。デフォルトでよい。 */
Velocity.init();
/* Context を作成して、データを入れる */
VelocityContext context = new VelocityContext();
context.put("name", "Velocity");
context.put("project", "Jakarta");
/* テンプレートを処理する */
StringWriter w = new StringWriter();
Velocity.mergeTemplate("testtemplate.vm", context, w );
System.out.println(" template : " + w );
/* 処理する文字列を作成する */
String s = "We are using $project $name to render this.";
w = new StringWriter();
Velocity.evaluate( context, w, "mystring", s );
System.out.println(" string : " + w );
}
}
|
 |
 |
 |
 |
When we run this program, and have the template testtemplate.vm
in the same directory as our program (because we used the default
configuration properties, and the defaul place to load templates
from is the current directory...), our output should be :
このプログラムを実行し、プログラムと同じディレクトリにtesttemplate.vm
というテンプレートを置きます (デフォルトの設定プロパティを使ったため、
テンプレートをロードするデフォルトの場所は現在のディレクトリになります)。
その結果、出力は以下のようになります。
 |
 |
 |
 |
template : Hi! This Velocity from the Jakarta project.
string : We are using Jakarta Velocity to render this.
|
 |
 |
 |
 |
where the template we used, testtemplate.vm, is
この際に使用したテンプレート(testtemplate.vm)は以下のとおりです。
 |
 |
 |
 |
Hi! This $name from the $project project.
|
 |
 |
 |
 |
That's all there is to it! Note that we didn't have to use both
mergeTemplate() and evaluate() in our
program. They are both included there for demonstration purposes.
You will probably use only one of the methods, but depending
on you application requirements, you are free to do what you wish.
これで完了です! プログラムで mergeTemplate() と evaluate()
の両方を使う必要はなかったことにご注意ください。両方入れたのはデモのためです。
恐らくどちらか1つだけを使うことになりますが、
アプリケーションの要件に応じて好きな処理を行なえます。
This appears to be a little different from the 'fundamental pattern'
that was mentioned at the beginning of this guide, but it really is the
same thing. First, you are making a context and filling it with
the data needed. Where this examples differs is that in the part of
the above example where mergeTemplate() is used,
mergeTemplate() is doing the work of getting the template
and merging it for you, using the lower-level calls in the Runtime class.
In the second example, you are making your template dynamically via the
String, so that is analgous to the 'choose template' part of the process,
and the evaluate() method does the merging for you using
lower level calls.
これはこのガイドの最初の方で説明した「基本パターン」と少し違うように見えますが、
実は同じパターンなのです。まず、コンテキストを作り、必要なデータで埋めています。
この例との違いですが、最初の例では、mergeTemplate() を使っている箇所で、
mergeTemplate() が Runtime クラスの低レベルの呼び出しを利用して、
テンプレートの取得とマージを行っています。第二の例では、
処理の「テンプレート選択」の部分に対応させるように、
String 経由で動的にテンプレートを生成し、低レベル呼び出しを行なう代わりに
evaluate() メソッドでマージを行っています。
So the example above sticks to the same simply pattern of using the Velocity
template engine, but the utility functions do some of
the repeated drudge work, or allow you other options for your
template content other than template files.
このように、上記の例では Velocity テンプレートエンジンを使用する際の
単純なパターンに合わせたわけですが、この他にも各ユーティリティメソッドは、
退屈な繰り返し作業を行ったり、
テンプレートファイル以外のテンプレート生成手段を提供したりします。
Exceptions
例外
There are three exceptions that Velocity will throw during the parse / merge cycle.
This are additional to the exceptions that will come from IO problems, etc.
They are found in the package org.apache.velocity.exception and are:
Velocity が、解析/マージのサイクルで投げる例外は3種類あります。これらの例外は、
I/O の問題などによる例外に追加するものです。org.apache.velocity.exception
パッケージにあるこれらの例外を以下に示します。
-
ResourceNotFoundException
Thrown when the resource managment system cannot find a resource (template) that
was requested.
-
ParseErrorException
Thrown when a VTL syntax error is found when parsing a resource (template).
-
MethodInvocationException
Thrown when a method of object in the context thrown an exception during
render time. This exception wraps the thrown exception and propogates it
to the application. This allows you to handle problems in your own objects
at runtime.
-
ResourceNotFoundException
リソース管理システムが要求されたリソース (テンプレート)
を見つけられない時に投げられます。
-
ParseErrorException
リソース (テンプレート) を解析するとき、VTL 構文エラーが見つかった時に投げられます。
-
MethodInvocationException
処理時にコンテキスト内のオブジェクトのメソッドで例外が投げられた場合に投げられます。
この例外は投げられた例外をラップしてアプリケーションに伝搬するためのものです。
これを使えば固有のオブジェクトで実行時に起こった問題を扱うことができます。
In each case, a message is put into the runtime log. For more information,
see the Javadoc API documentation.
どの場合でもメッセージはランタイムログに入ります。
詳細は、Javadoc API ドキュメンテーションをご覧下さい。
Miscellaneous Details
その他雑記
While the above example used the default properties, setting your own
properties is very simple. All you have to do is make a properties file
somewhere and pass the name of that file to the init(String)
method of the Velocity utility class, or make a
java.util.Properties object, add the desired properties and
values, and pass that to the init(Properties) method.
The latter method is convenient, because you can either fill it directly
from a separate properties file via the load() method, or even
better, you can fill it dynamically from your own application / framework's
property set at runtime. This gives you the freedom to combine all of the
properties for your app into one properties file.
上記の例ではデフォルトのプロパティが使われていましたが、
固有のプロパティ設定はとても簡単です。どこかにプロパティファイルを作り、
そのファイル名を Velocity ユーティリティクラスの init(String)
メソッドに渡す方法と、java.util.Properties オブジェクトを作り、
好きなプロパティと値を加え、それを init(Properties)
メソッドに渡す方法があります。後者の方法の方が便利です。
というのは、load() メソッドを使って、
別々のプロパティファイルから直接設定したり、
もっといい方法として、実行時にアプリケーション/フレームワークの
プロパティセットから動的に設定することができるからです。
これによって、自分のアプリのプロパティ全てを、
1つのプロパティファイルにまとめることができるのです。
If we wanted to use a different directory than the current directory to
load our template from, we could do something like this :
テンプレートをロードするのにカレントディレクトリ以外のディレクトリを使いたい場合には、
以下のようにもできます。
 |
 |
 |
 |
...
import java.util.Properties;
...
public static void main( String args[] )
{
/* first, we init the runtime engine. */
Properties p = new Properties();
p.setProperty("file.resource.loader.path", "/opt/templates");
Velocity.init( p );
/* lets make a Context and put data into it */
...
|
 |
 |
 |
 |
 |
 |
 |
 |
...
import java.util.Properties;
...
public static void main( String args[] )
{
/* まずは、実行エンジンを初期化する */
Properties p = new Properties();
p.setProperty("file.resource.loader.path", "/opt/templates");
Velocity.init( p );
/* Contextを作ってデータを入れる */
...
|
 |
 |
 |
 |
And, assuming you have a directory /opt/templates and the template
testtemplate.vm is in there, then things would work just fine.
If you try this and have a problem, be sure to look at the velocity.log for
information - the error messages are pretty good for figuring out what is wrong.
ディレクトリ /opt/templates があり、そこにテンプレート
testtemplate.vm がある場合に、これはうまく動きます。
これを試して問題があるなら、情報を得るために velocity.log をチェックして下さい ─
エラーメッセージは何がおかしいか理解するためにかなり役立ちます。
|
|
|
Application Attributes − アプリケーション属性
|
Application Attributes are name-value pairs that can be associated with
a RuntimeInstance (either via the VelocityEngine or
the Velocity singleton) and accessed from any part of the Velocity
engine that has access to the RuntimeInstance.
アプリケーション属性 は、(VelocityEngine、
Velocity Singleton のどちらかを経由して) RuntimeInstance
に関連付けられる名前と値のペアです。RuntimeInstance にアクセスできる VeclocityEngine
のどの部分からでもアクセスできます。
This feature was designed for applications that need to communicate between
the application layer and custom parts of the Velocity engine, such as
loggers, resource loaders, resource managers, etc.
この機能は、アプリケーションレイヤと Velocity エンジンのカスタムの部分
(ロガー、リソースローダ、リソースマネージャなど)
の間でのデータの受け渡しが必要なアプリケーションのために用意しました。
The Application Attribute API is very simple. From the application layer, there
is a method of the VelocityEngine and the Velocity
classes :
アプリケーション属性 API は非常に単純です。
アプリケーションからアクセスするメソッドとしては、VelocityEngine と
Velocity クラスに以下のメソッドがあります。
 |
 |
 |
 |
public void setApplicationAttribute( Object key, Object value );
|
 |
 |
 |
 |
through which an application can store on Object under an application (or
internal component) specified key. There are no restrictions on the key
or the value. The value for a key may be set at any time - it is not required
that this be set before init() is called.
このメソッドを使うと、アプリケーション (または内部コンポーネント)
固有のキーで Object を保存できます。キーや値に制限はありません。
キーの値はいつでも設定できます ─ init() が呼ばれる前に設定する必要はありません。
Internal components can access the key-value pairs if they have access to the
object via the RuntimeServices interface, using the method
内部コンポーネントが RuntimeServices
インタフェース経由でオブジェクトにアクセスする場合は、以下のメソッドを使って、
キーと値のペアにアクセスできます。
 |
 |
 |
 |
public Object getApplicationAttribute( Object key );
|
 |
 |
 |
 |
Note that internal components cannot set the value of the key, just get it.
if the internal component must communicate information to the application layer,
it must do so via the Object passed as the value.
内部コンポーネントではキーの値の取得はできても、設定はできないことに注意して下さい。
内部コンポーネントがアプリケーションと情報の受け渡しをしなければならない場合は、
値として渡される Object 経由でなければなりません。
|
|
|
EventCartridge and Event Handlers − EventCartridge とイベントハンドラ
|
Starting in version 1.1, a fine-grain event handling system was added to Velocity.
The EventCartridge is a class in which you register your event handlers, and then the
EventCartridge acts as the delivery agent from which the Velocity engine will
access the event handlers at merge time if needed.
Currently, there are 3 events that can be handled, and all are found in the
org.apache.velocity.app.event package.
バージョン 1.1 から、Velocity にきめの細かいイベントハンドリングシステムが追加されました。
EventCartridge はイベントハンドラを登録するためのクラスで、さらに、
必要ならば、マージ時に登録したイベントハンドラにアクセスするための
デリバリエージェントとしても動作します。
現在、ハンドルできるイベントは3つで、すべて org.apache.velocity.app.event
パッケージにあります。
org.apache.velocity.app.event.NullSetEventHandler
When a #set() results in a null assignment, this is normally
logged. The NullSetEventHandler allows you to 'veto' the
logging of this condition.
public interface NullSetEventHandler extends EventHandler
{
public boolean shouldLogOnNullSet( String lhs, String rhs );
}
org.apache.velocity.app.event.ReferenceInsertionEventHandler
A ReferenceInsertionEventHandler allows the
developer to intercept each write of a reference ($foo) value to the output
stream and modify that output.
public interface ReferenceInsertionEventHandler extends EventHandler
{
public Object referenceInsert( String reference, Object value );
}
org.apache.velocity.app.event.MethodExceptionEventHandler
When a user-supplied method throws an exception, the
MethodExceptionEventHandler is invoked with the Class, method name
and thrown Exception. The handler can either return a valid Object to be used
as the return value of the method call, or throw the passed-in or new Exception,
which will be wrapped and propogated to the user as a
MethodInvocationException
public interface MethodExceptionEventHandler extends EventHandler
{
public Object methodException( Class claz, String method, Exception e )
throws Exception;
}
org.apache.velocity.app.event.NullSetEventHandler
#set() で null が代入された場合、通常はログに記録されます。
NullSetEventHandler を使うと、こうした場合にロギングを「拒否」できます。
public interface NullSetEventHandler extends EventHandler
{
public boolean shouldLogOnNullSet( String lhs, String rhs );
}
org.apache.velocity.app.event.ReferenceInsertionEventHandler
ReferenceInsertionEventHandler を使うと、リファレンス ($foo) の値の
出力ストリームへの書き出しに割り込んで、出力内容を変更できます。
public interface ReferenceInsertionEventHandler extends EventHandler
{
public Object referenceInsert( String reference, Object value );
}
org.apache.velocity.app.event.MethodExceptionEventHandler
ユーザが作成したメソッドから例外が投げられた時に、
MethodExceptionEventHandler が、関連する Class やメソッド名、
投げられた例外とともに起動します。このハンドラは、メソッド呼び出しの返り値
として使われる使われる有効なオブジェクトを返すか、
引数として渡された例外、あるいは新しい例外を投げます。新しい例外の場合は、
MethodInvocationException としてラップされてユーザに伝搬されます。
public interface MethodExceptionEventHandler extends EventHandler
{
public Object methodException( Class claz, String method, Exception e )
throws Exception;
}
Using the EventCartridge
EventCartridge の使い方
Using the EventCartridge is fairly straightforward. The following abbreviated
example was taken from org.apache.velocity.test.misc.Test.
EventCartridge の使い方はとても簡単です。
以下の例は、org.apache.velocity.test.misc.Test から抜粋したものです。
 |
 |
 |
 |
...
import org.apache.velocity.app.event.EventCartridge;
import org.apache.velocity.app.event.ReferenceInsertionEventHandler;
import org.apache.velocity.app.event.MethodExceptionEventHandler;
import org.apache.velocity.app.event.NullSetEventHandler;
...
public class Test implements ReferenceInsertionEventHandler,
NullSetEventHandler,
MethodExceptionEventHandler
{
public void myTest()
{
....
/*
* now, it's assumed that Test implements the correct methods to
* support the event handler interfaces. So to use them, first
* make a new cartridge
*/
EventCartridge ec = new EventCartridge();
/*
* then register this class as it contains the handlers
*/
ec.addEventHandler(this);
/*
* and then finally let it attach itself to the context
*/
ec.attachToContext( context );
/*
* now merge your template with the context as you normally
* do
*/
....
}
/*
* and now the implementations of the event handlers
*/
public Object referenceInsert( String reference, Object value )
{
/* do something with it */
return value;
}
public boolean shouldLogOnNullSet( String lhs, String rhs )
{
if ( /* whatever rule */ )
return false;
return true;
}
public Object methodException( Class claz, String method, Exception e )
throws Exception
{
if ( /* whatever rule */ )
return "I should have thrown";
throw e;
}
}
|
 |
 |
 |
 |
 |
 |
 |
 |
...
import org.apache.velocity.app.event.EventCartridge;
import org.apache.velocity.app.event.ReferenceInsertionEventHandler;
import org.apache.velocity.app.event.MethodExceptionEventHandler;
import org.apache.velocity.app.event.NullSetEventHandler;
...
public class Test implements ReferenceInsertionEventHandler,
NullSetEventHandler,
MethodExceptionEventHandler
{
public void myTest()
{
....
/*
* ここでは、Test クラスは、イベントハンドラインタフェースを
* サポートするように正しいメソッドを実装していると仮定します。
* これらを使うにはまず、カートリッジを新しく作ります。
*/
EventCartridge ec = new EventCartridge();
/*
* そして、このクラスをハンドラに収容するように登録します
*/
ec.addEventHandler(this);
/*
* 最後に カートリッジそのものをコンテキストに取り付けます。
*/
ec.attachToContext( context );
/*
* あとは、いつものようにコンテキストをテンプレートにマージします。
*/
....
}
/*
* ここで、イベントハンドラの実装を行ないます。
*/
public Object referenceInsert( String reference, Object value )
{
/* リファレンスを使って何かします */
return value;
}
public boolean shouldLogOnNullSet( String lhs, String rhs )
{
if ( /* 何らかのルール */ )
return false;
return true;
}
public Object methodException( Class claz, String method, Exception e )
throws Exception
{
if ( /* 何らかのルール */ )
return "I should have thrown";
throw e;
}
}
|
 |
 |
 |
 |
|
|
|
Velocity Configuration Keys and Values − Velocity 設定キーと値
|
Velocity's runtime configuration is controlled by a set of configuration keys
listed below. Generally, these keys will have values that consist of either a
String, or a comma-separated list of Strings, referred to as a CSV for
comma-separated values.
Velocity の実行時構成は、以下の一覧にある各設定キーで制御します。
通常、これらのキーは String の値、あるいは CSV (Comma Separated Values)
と呼ばれるコンマ区切りの String のリストの値を持ちます。
There is a set of default values contained in Velocity's jar, found in
/src/java/org/apache/velocity/runtime/defaults/velocity.defaults, that
Velocity uses as it's configuration baseline.
This ensures that Velocity will always have a 'correct' value
for it's configuration keys at startup, although it may not be what you want.
各デフォルト値は Velocity の JAR ファイルに含まれており、ソースとしては
/src/Java/org/apache/velocity/runtime/defaults/velocity.defaults にあり、
Velocity はこれらを設定のベースラインとして使います。
これにより、 Velocity の起動時に設定キーに常に「正しい」値が入っていることが
保証されますが、それはあなたが求めている値だとは限りません。
Any values specified before init() time will replace the default values.
Therefore, you only have toconfigure velocity with the values for the keys
that you need to change, and not worry about the rest. Further, as we add more
features and configuration capability, you don't have to change your
configuration files to suit - the Velocity engine will always have default
values.
init() の実行前に値を指定すると、デフォルトの値を置き換えられます。
したがって、Velocity では変更が必要なキーの値だけを設定すればよく、それ以外は
気にする必要はありません。さらに、設定関連を含めて多くの機能が追加されても、
それに合わせて設定ファイルを変更する必要はありません ─ Velocity エンジンは、
常にデフォルト値を持っているからです。
Please sees the section above Using Velocity In General
Applications for discussion on the configuration API.
設定 API についての詳細は上のセクション
一般的なアプリケーションで Velocity を使う を参照してください。
Below are listed the configuration keys that control Velocity's behavior.
Organized by category, each key is listed with it's current default value
to the right of the '=' sign.
Velocity の動作を制御する設定キーの一覧は以下の通りです。
各キーはカテゴリ別に分類され、「=」記号の後に現在のデフォルト値を示しています。
Runtime Log
Runtime Log
runtime.log = velocity.log
Full path and name of log file for error, warning,
and informational messages. The location, if not absolute, is
relative to the 'current directory'.
runtime.log = velocity.log
エラー、警告、情報に関するメッセージのためのログファイルのフルパスと名前。
格納場所は、絶対パスでなければ、「カレントディレクトリ」の相対パスとなります。
runtime.log.logsystem
This property has no default value. It is used to give Velocity an
instantiated instance of a logging class that supports the interface
org.apache.velocity.runtime.log.LogSystem., which allows
the combination of Velocity log messages with your other application
log messages. Please see the section
Configuring the Log System
for more information.
runtime.log.logsystem
このプロパティには、デフォルトの値がありません。このキーは Velocity でロギングクラス
のインスタンスを使うのに使用します。ロギングクラスは
org.apache.velocity.runtime.log.LogSystem インタフェースをサポートします。
このインタフェースを使えば、 Velocity のログメッセージと
アプリケーションのログメッセージを同じログに入れることができます。詳細は、
一般的なアプリケーションで
Velocity を使う のセクションをご覧ください。
runtime.log.logsystem.class =
org.apache.velocity.runtime.log.AvalonLogSystem
Class to be used for the Velocity-instantiated log system.
runtime.log.logsystem.class =
org.apache.velocity.runtime.log.AvalonLogSystem
Velocity がインスタンス化したログシステムで使用されるクラスです。
runtime.log.error.stacktrace = false
runtime.log.warn.stacktrace = false
runtime.log.info.stacktrace = false
Turns on stacktracing for the three error categories.
These produce a large amount of log output.
runtime.log.error.stacktrace = false
runtime.log.warn.stacktrace = false
runtime.log.info.stacktrace = false
true にすると、これらのエラーカテゴリーのスタックトレースを有効にします。
これは大量のログを生成します。
runtime.log.invalid.references = true
Property to turn off the log output when a reference isn't valid.
Good thing to turn of in production, but very valuable
for debugging.
runtime.log.invalid.references = true
false にすると、リファレンスが無効な場合もログ出力されません。
本番環境では false にすると良いのですが、
デバッグ時には [trueにしておくと] とても役立ちます。
runtime.log.logsystem.avalon.logger = name
Allows user to specify an existing logger name
in the Avalon hierarchy
without having to wrap with a LogSystem interface. Note:
You must also specify
runtime.log.logsystem.class =
org.apache.velocity.runtime.log.AvalonLogSystem as the default
logsystem may change. There is no guarantee that the Avalon
log system will remain the default log system.
runtime.log.logsystem.avalon.logger = name
これを使うと、ユーザは Avalon 階層内の既存のロガーを LogSystem インタフェースで
ラップしなくても name で指定できます。
注意: デフォルトのログシステムは変更される可能性があるため、この設定とともに
runtime.log.logsystem.class =
org.apache.velocity.runtime.log.AvalonLogSystem と指定しなければ
なりません。また Avalon ログシステムが将来もデフォルトのログシステムであることは
保証されていません。
Character Encoding
文字エンコーディング
input.encoding = ISO-8859-1
Character encoding for input (templates). Using this, you can use
alternative encoding for your templates, such as UTF-8.
input.encoding = ISO-8859-1
入力 (テンプレート) の文字エンコーディングを指定します。
これを使うと、テンプレートで UTF-8 といった別のエンコーディングを使用できます。
output.encoding = ISO-8859-1
Character encoding for output streams from the VelocityServlet and Anakia.
output.encoding = ISO-8859-1
VelocityServlet と Anakia からの出力ストリームのための文字エンコーディング
#foreach() Directive
#foreach() 指示子
directive.foreach.counter.name = velocityCount
Used in the #foreach() directive, defines the string to be used as the
context key for the loop count. A template would access
the loop count as $velocityCount.
directive.foreach.counter.name = velocityCount
#foreach() 指示子で使用され、ループカウントのためのコンテキストキー
として使用される文字列を定義します。テンプレートでは、このループカウントに
$velocityCount でアクセスできます。
directive.foreach.counter.initial.value = 1
Default starting value for the loop counter reference in a #foreach() loop.
directive.foreach.initial.value = 1
#foreach() ループでのループカウンタリファレンスのためのデフォルトの開始値
#include() and #parse() Directive
#include() と #parse() 指示子
directive.include.output.errormsg.start
=
directive.include.output.errormsg.end
= ]]>
Defines the beginning and ending tags for an in-stream error message in the
case of a problem with the #include() directive. If both the .start and .end
tags are defined, an error message will be output to the stream, of the
form '.start msg .end' where .start and .end refer to the property values.
Output to the render stream will only occur if both the .start and .end
(next) tag are defined.
directive.include.output.errormsg.start
= <!-- include error :
directive.include.output.errormsg.end
= see error log -->
#include() 指示子で問題が起こった場合の、入力ストリームのエラーメッセージ用に
開始タグと終了タグを定義します。.start と .end の両方でタグが定義されていれば、
エラーメッセージは、「.start msg .end」という形式
(この形式では .start と .end でプロパティの値を参照します) で、
ストリームに出力されます。
.start と .end の両方で(次の)タグが定義されていても、
テンプレート処理ストリームへの出力が行われるだけです。
directive.parse.maxdepth = 10
Defines the allowable parse depth for a template. A template may #parse()
another template which itself may have a #parse() directive. This value
prevents runaway #parse() recursion.
directive.parse.maxdepth = 10
テンプレート解析の深度を定義します。
テンプレートは、別のテンプレートを #parse() するかも知れませんし、
解析されるテンプレートにも #parse() 指示子があるかもしれません。
この値は、#parse() 再帰の無限ループを防ぎます。
Resource Management
リソース管理
resource.manager.logwhenfound = true
Switch to control logging of 'found' messages from resource manager.
When a resource is found for the first time, the resource name
and classname of the loader that found it will be noted in the
runtime log.
resource.manager.logwhenfound = true
リソースマネージャからの「リソース発見」メッセージの
ロギングの制御を切り替えます。最初にリソースが見つかったときに、
リソース名とリソースを見つけたローダのクラス名が
ランタイムログに通知されます。
resource.loader = <name> (default = File)
Multi-valued key. Will accept CSV for value. Pulic name of a
resource loader to be used. This public name will then be used
in the specification of the specific properties for that resource loader.
Note that as a multi-valued key, it's possible to pass
a value like "file, class" (sans quotes), indicating that following
will be configuration values for two loaders.
resource.loader = <name> (default = File)
複数値のキーで、値として CSV 形式を受け入れます。
リソースローダのパブリック名が使用されます。このパブリック名は、
このリソースローダに固有のプロパティを指定するのに使用されます。
注意: 複数値のキーでは、"file, class" (引用符なし) といった値を渡すことが可能で、
上記の値の場合、2つのローダの設定値が後に続くことを示しています。
<name>.loader.description
= Velocity File Resource Loader
Description string for the given loader.
<name>.loader.description
= Velocity File Resource Loader
当該ローダの説明文字列。
<name>.resource.loader.class
= org.apache.velocity.runtime.resource.loader.FileResourceLoader
Name of implementation class for the loader. The default loader
is the file loader.
<name>.resource.loader.class
= org.apache.velocity.runtime.resource.loader.FileResourceLoader
このローダのクラスの実装名。デフォルトのローダはファイルローダです。
<name>.resource.loader.path = .
Multi-valued key. Will accept CSV for value. Root(s) from which the
loader loads templates. Templates may live in subdirectories of this root.
ex. homesite/index.vm This configuration key applies currently to the
FileResourceLoader and JarResourceLoader.
<name>.resource.loader.path = .
複数値のキーで、値として CSV 形式を受け入れます。
ローダによるテンプレートの読み込み元のルートを示します。テンプレートは
このルートのサブディレクトリに存在しているかもしれません。
例) homesite/index.vm。この設定キーは、現在のところ
FileResourceLoader と JarResourceLoader に適用されます。
<name>.resource.loader.cache = false
Controls caching of the templates in the loader. Default is false, to make
life easy for development and debugging. This should be set to true for
production deployment. When 'true', the modificationCheckInterval
property applies. This allows for the efficiency of caching, with the
convenience of controlled reloads - useful in a hosted or ISP environment
where templates can be modifed frequently and bouncing the application or
servlet engine is not desired or permitted.
<name>.resource.loader.cache = false
ローダでのテンプレートのキャッシュ制御。
配備とデバッグを簡単にするために、デフォルトは false となっています。
本番環境への配備の際に true にすべきです。
「true」の場合は modificationCheckInterval プロパティが適用されます。
これによって、キャッシュを効率的に行ない、リロード制御を簡単に行なえます ──
これは、テンプレートは頻繁に変更されるけれども、アプリケーションやサーブレットエンジンの
再起動はしたくない、あるいは許可されていないようなホスティング環境や ISP 環境
で役に立ちます。
<name>.resource.loader.modificationCheckInterval = 2
This is the number of seconds between modification checks when caching is
turned on. When this is an integer > 0, this represents the number of
seconds between checks to see if the template was modified. If the
template has been modified since last check, then it is reloaded and
reparsed. Otherwise nothing is done. When <= 0, no modification
checks will take place, and assuming that the property cache
(above) is true, once a template is loaded and parsed the first time it is used,
it will not be checked or reloaded after that until the application or
servlet engine is restarted.
<name>.resource.loader.modificationCheckInterval = 2
キャッシュが有効な場合の変更チェックの間隔の秒数です。
この数字が 0 より大きい整数の場合、テンプレートが変更されたかどうかを
チェックする間隔の秒数を示します。最後のチェック以降にテンプレートが
変更されていれば、再ロード・再解析されます。そうでなければ、何もしません。
0 以下の場合は修正チェックは行われませんし、 (上記の) cache プロパティ
が true の場合、テンプレートが最初の使用時に一度ロード・解析されたら、
アプリケーションやサーブレットエンジンが再起動するまでチェック・リロードは行れません。
To illustrate, here is an example taken right from the default Velocity
properties, showing how setting up the FileResourceLoader is managed
具体例として、デフォルトの Velocity プロパティで FileResourceLoader のセットアップ
がどのように管理されているかを示します。
 |
 |
 |
 |
resource.loader = file
file.resource.loader.description = Velocity File Resource Loader
file.resource.loader.class = org.apache.velocity.runtime.resource.loader.FileResourceLoader
file.resource.loader.path = .
file.resource.loader.cache = false
file.resource.loader.modificationCheckInterval = 2
|
 |
 |
 |
 |
Velocimacro
Velocimacro
velocimacro.library = VM_global_library.vm
Multi-valued key. Will accept CSV for value.
Filename(s) of Velocimacro library to be loaded when the Velocity
Runtime engine starts. These Velocimacros are accessable to all
templates. The file is assumed to be relative to the root of the
file loader resource path.
velocimacro.library = VM_global_library.vm
複数値のキーで、値としてCSV形式を受け入れます。
Velocity Runtime エンジンが起動したときにロードされる
Velocimacro ライブラリのファイル名(複数指定可)です。これらの Velocimacro は、
すべてのテンプレートからアクセスできます。このファイルでは
ファイルローダリソースパスのルートからの相対パスを想定しています。
velocimacro.permissions.allow.inline = true
Determines of the definition of new Velocimacros via the #macro() directive
in templates is allowed. The default value is true, meaning any template
can define and use new Velocimacros. Note that depending on other properties,
those #macro() statements can replace global definitions.
velocimacro.permissions.allow.inline = true
テンプレート内で #macro() 指示子による新しい Velocimacro の定義を許可するかどうか
を決定します。デフォルト値は true で、どんなテンプレートでも新しいVelocimacro
の定義・使用が可能であることを意味します。
注意: 他のプロパティの設定によっては、これらの #macro() ステートメントが
グローバルな定義を置き換えることも可能です。
velocimacro.permissions.allow.inline.to.replace.global = false
Controls if a Velocimacro defind 'inline' in a template can replace
a Velocimacro defined in a library loaded at startup.
velocimacro.permissions.allow.inline.to.replace.global = false
テンプレート内で「インライン」定義された Velocimacro が、起動時にロードされた
ライブラリ内の Velocimacro 定義を置換できるかどうか制御します。
velocimacro.permissions.allow.inline.local.scope = false
Controls 'private' templates namespaces for Velocimacros. When true, a #macro()
directive in a template creates a Velocimacro that is accessable only from the
defining template. This means that Velocimacros cannot be shared unless they
are in the global or local library loaded at startup. (See above.) It also means
that templates cannot interfere with each other. This property also allows a technique
where there is a 'default' Velocimacro definition in the global or local library,
and a template can 'override' the implementation for use within that template.
This occurrs because when this property is true, the template's namespace is
searched for a Velocimacro before the global namespace, therefore allowing
the override mechanism.
velocimacro.permissions.allow.inline.local.scope = false
Velocimacro の「プライベートな」テンプレートのネームスペースを制御します。
true のとき、テンプレート内の #macro() 指示子で作成した Velocimacro は、
定義を行ったテンプレートからのみアクセスできます。つまり、起動時にロードされる
グローバル/ローカルのライブラリ以外の Velocimacro は共有できないことを意味します (上記参照)。また、テンプレートが相互干渉できないことも意味します。
このプロパティを使うと、グローバル/ローカルのライブラリに「デフォルト」の
Velocimacro 定義があり、テンプレート内の使用時にその実装を「オーバーライド」するという
テクニックが可能です。こうしたことが可能なのは、このプロパティが true の場合、
Velocimacro でのテンプレートのネームスペースの検索がグローバルネームスペースより
先に行われ、オーバーライドを行なうことが可能となるためです。
velocimacro.context.localscope = false
Controls whether reference access (set/get) within a Velocimacro will change
the context, or be of local scope in that
Velocimacro.
velocimacro.context.localscope = false
Velocimacro 内のリファレンスへのアクセス (set/get) でコンテキストを変更できるようにするか、
それとも、アクセスはその Velocimacro のローカルスコープに限定するかを決めます。
velocimacro.library.autoreload = false
Controls Velocimacro library autoloading. When set to true
the source Velocimacro library for an invoked Velocimacro will be checked
for changes, and reloaded if necessary. This allows you to change and
test Velocimacro libraries without having to restart your application or
servlet container, just like you can with regular templates.
This mode only works when caching is off
in the resource loaders (e.g. file.resource.loader.cache = false ).
This feature is intended for development, not for production.
velocimacro.library.autoreload = false
Velocimacro ライブラリの自動ロードを制御します。
trueにセットすると、起動された Velocimacro のライブラリソースについて
変更をチェックし、必要であればリロードされます。
これにより、まさに通常のテンプレートと同じように、
アプリケーションやサーブレットコンテナを再起動せずに
Velocimacro ライブラリの変更・テストができるようになります。
これは、リソースローダのキャッシュが off (例えば
file.resource.loader.cache = false ) の場合のみ動作します。
この機能は開発用であり本番環境用ではありません。
String Interpolation
文字列展開
runtime.interpolate.string.literals = true
Controls interpolation mechanism of VTL String Literals. Note that a VTL
StringLiteral is specifically a string using double quotes that is used
in a #set() statement, a method call of a reference, a parameter to a VM,
or as an argument to a VTL directive in general. See the VTL reference for
further information.
runtime.interpolate.string.literals = true
VTL String リテラルの展開の仕組みを制御します。注意:
VTL String リテラルは厳密に言えば二重引用符で囲まれた文字列で、
#set() ステートメント内、リファレンスのメソッド呼び出し、VM へのパラメータで使われたり、
VTL 指示子への引数として一般的に使われたりします。
詳細は VTL リファレンスを見てください。
Runtime Configuration
ランタイム設定
parser.pool.size = 20
This property sets the number of parsers that Velocity will
create at startup and keep in a pool. The default of 20 parsers
should be more than enough for most uses. In the event
that Velocity does run out of parsers, it will indicate
so in the log, and
dynamically create them as needed. Note that they will not
be added to the pool. This is a slow operation compared to
the normal parser pooling, but this is considered an
exceptional condition. If you see a log message, please
increment this property.
parser.pool.size = 20
このプロパティでは、Velocity が起動時に作成して、プールに保持する
パーサの数を設定します。
デフォルトのパーサ数は20ですが、たいていの用途では十分なはずです。
Velocity がパーサを使い果たすと、ログに記録され、必要に応じて動的に
作成されます。ただし、それらはプールに加えられないことに注意してください。
通常のパーサのプールと比較して動作が遅くなりますが、
これは例外的な状態だと考えられます。ログにメッセージが出た場合には、
このプロパティの数字を増やしてください。
Pluggable Introspection
runtime.introspector.uberspect =
org.apache.velocity.util.introspection.UberspectImpl
This property sets the 'Uberspector', the introspection package that
handles all introspection strategies for Velocity. The default works just
fine, so only replace if you have something really interesting and special
to do.
|
|
|
Configuring the Log System − ログシステム設定
|
Velocity has a few nice logging features to allow both simplicity and
flexibility. Without any extra configuration, Velocity will setup a
file-based logger that will output all logging messages to a file
called velocity.log in the 'current directory' where
Velocity was initialized. For more advanced users, you may integrate
your current logging facilities with Velocity to have all log messages
sent to your logger.
Velocity には、シンプルかつ柔軟な、優れたロギング機能がいくつかあります。
特に設定をしなくても、Velocity はファイルベースのロガーをセットアップします。
このロガーはすべてのログメッセージを Velocity が起動した「カレントディレクトリ」
に velocity.log という名前のファイルで出力します。
より高度な使い方をするユーザのために、既存のロギング機能と Velocity を統合し、
全てのログメッセージを既存のロガーに出力することも可能です。
Starting with version 1.3, Velocity will automatically use either the
Jakarta Avalon Logkit logger, or the
Jakarta Log4j logger.
It will do so by using whatever it finds in the current classpath, starting
first with Logkit. If Logkit isn't found, it tries Log4j.
バージョン 1.3 から、
Avalon Logkit
ロガーと Jakarta Log4j
ロガーのどちらかを自動選択するようになりました。
現在のクラスパスで見つかった方を選択しますが、もし両方ある場合は Logkit を選択します。もし Logkit がなければ Log4j があるかどうか確認します。
To utilize this feature, simply use the 'non-dependency' Velocity jar
(because Logkit is baked into the jar with dependencies) and place
either the logkit or log4j jar in your classpath.
この機能を使う手順としては、「依存ライブラリなしの」Velocity JAR ファイルを使い、
(依存ライブラリ込みの JAR ファイルの場合は、Logkit が埋め込まれているので)、
Logkit か Log4j の どちらかの JAR ファイルをクラスパスに含めるだけです。
In general, you have the following logging options :
ロギングについては、通常は以下の選択肢があります。
-
Default Configuration
By default, Velocity will create a file-based logger in the current
directory. See the note above regarding automatic detection of
Logkit or Log4j to use as the default logging system.
-
Existing Log4j Category
Starting with version 1.3, Velocity will log it's output to an existing
Log4j Category setup elsewhere in the application. To use this feature
you must
-
Make sure that the Log4j jar is in your classpath. (You would do this
anyway since you are using Log4j in the application using Velocity.)
-
Configure Velocity to use the
SimpleLog4JLogSystem class.
-
Specify the name of the existing Category to use via the
'runtime.log.logsystem.log4j.category' property.
This approach replaces and deprecates the older Log4JLogSystem
class. To see how this is done in code, see the example below.
-
Custom Standalone Logger
You can create a custom logging class - you simply must implement the
interface org.apache.velocity.runtime.log.LogSystem and
then simply set the configuration property
runtime.log.logsystem.class with the
classname, and Velocity will create an instance of that class at init time.
You may specify the classname as you specify any other properties. See
the information on the
Velocity helper class as well as the
configuration keys and values.
Please note that through oversight, the interface to
org.apache.velocity.runtime.log.LogSystem
was changed in v1.2 to support the separable instances of the Velocity
runtime. If you have an exisiting pre v1.2 custom logger that is going
to be instantiated by the Velocity LogManager, you must add the
init( RuntimeServices ) method.
-
Integrated Logging
You can integrate Velocity's logging capabilities with your applications
existing logging system, simply by implementing the
org.apache.velocity.runtime.log.LogSystem interface. Then,
pass an instance of your logging class to Velocity via the
runtime.log.logsystem configuration key before
initializing the Velocity engine,
and Velocity will log messages to your applications logger.
See the information on the
Velocity helper class
as well as the
configuration keys and values.
-
デフォルト設定
デフォルトでは、Velocity はファイルベースのログをカレントディレクトリに作成します。
-
既存の Log4j カテゴリ
バージョン 1.3 から、Velocity ではアプリケーションの他のところでセットアップした、
既存の Log4j カテゴリにログ出力できるようになりました。この機能を使うためには、
以下のようにする必要があります。
-
Log4j の JAR ファイルがクラスパスに含まれていることを確認する。
(Velocity を使ったアプリケーションで Log4j を使っているなら、
何はともあれこの作業を行なうでしょう)
-
SimpleLog4JLogSystem を使うように Velocity を設定する。
-
'runtime.log.logsystem.log4j.category' プロパティに、
既存のカテゴリの名前を指定する。
このアプローチは今までの Log4JLogSystem クラスを置き換えるもので、
このクラスは非推奨となります。コードでの例については後述します。
-
カスタムのスタンドアロンのロガー
カスタムロギングクラスを作成することもできます --
org.apache.velocity.runtime.log.LogSystem インタフェースを実装し、
設定プロパティ runtime.log.logsystem.class にクラス名を設定するだけでよく、
そうすれば Velocity は 初期化時にそのクラスのインスタンスを生成します。
他のプロパティも指定するのと同様に、別のクラス名の指定もできます。
詳細については、Velocity ヘルパクラス と
Velocity 設定キーと値 を参照してください。
-
統合ロギング
org.apache.velocity.runtime.log.LogSystem インタフェースを実装するだけで、
Velocity のロギング機能をあなたのアプリケーションの既存のロギングシステムと
統合できます。そして、 init() を呼ぶ前に runtime.log.logsystem 設定キーを
使って Velocity にロギングクラスのインスタンスを渡せば、 Velocity はアプリケーションの
ロガーにメッセージを送るようになります。詳細は、
Velocity ヘルパクラスと
Velocity 設定キーと値 を参照してください。
Using Log4j With Existing Category
既存のカテゴリで Log4j を使う
Here is an example of how to configure Velocity to log to an existing Log4j
Category.
既存の Log4j カテゴリでログ出力を行なうように Velocity を設定する方法の例を示します。
 |
 |
 |
 |
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.log4j.Category;
import org.apache.log4j.BasicConfigurator;
public class Log4jCategoryExample
{
public static String CATEGORY_NAME = "velexample";
public static void main( String args[] )
throws Exception
{
/*
* configure log4j to log to console
*/
BasicConfigurator.configure();
Category log = Category.getInstance( CATEGORY_NAME );
log.info("Hello from Log4jCategoryExample - ready to start velocity");
/*
* now create a new VelocityEngine instance, and
* configure it to use the category
*/
VelocityEngine ve = new VelocityEngine();
ve.setProperty( RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
"org.apache.velocity.runtime.log.SimpleLog4JLogSystem" );
ve.setProperty("runtime.log.logsystem.log4j.category", CATEGORY_NAME);
ve.init();
log.info("this should follow the initialization output from velocity");
}
}
|
 |
 |
 |
 |
 |
 |
 |
 |
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.log4j.Category;
import org.apache.log4j.BasicConfigurator;
public class Log4jCategoryExample
{
public static String CATEGORY_NAME = "velexample";
public static void main( String args[] )
throws Exception
{
/*
* Log4j でログに出力するよう設定する。
*/
BasicConfigurator.configure();
Category log = Category.getInstance( CATEGORY_NAME );
log.info("Hello from Log4jCategoryExample - ready to start velocity");
/*
* ここで VelocityEngine インスタンスを生成し、
* このカテゴリを使うよう設定する。
*/
VelocityEngine ve = new VelocityEngine();
ve.setProperty( RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
"org.apache.velocity.runtime.log.SimpleLog4JLogSystem" );
ve.setProperty("runtime.log.logsystem.log4j.category", CATEGORY_NAME);
ve.init();
log.info("this should follow the initialization output from velocity");
}
}
|
 |
 |
 |
 |
Note that the above example can be found in examples/logger_example.
この例は、examples/logger_example にあります。
Simple Example of a Custom Logger
カスタムロガーの単純な例
Here is an example of how to use an instantiation of your class that implements
Velocity's logging system as the logger. Note that we are not passing the name
of the class to use, but rather a living, existing instantiation of the class
to be used. All that is required is that it support the
LogSystem interface.
Velocity のロギングシステムをロガーとして実装するクラスのインスタンス化の例です。
使用するクラス名ではなく、
使用するクラスの実際に存在するインスタンスを渡しているところに注意してください。
必須なのは、LogSystem インタフェースをサポートすることだけです。
 |
 |
 |
 |
import org.apache.velocity.runtime.log.LogSystem;
import org.apache.velocity.runtime.RuntimeServices;
...
public class MyClass implements LogSystem
{
...
public MyClass()
{
...
try
{
/*
* register this class as a logger
*/
Velocity.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM, this );
Velocity.init();
}
catch (Exception e)
{
/*
* do something
*/
}
}
/**
* This init() will be invoked once by the LogManager
* to give you current RuntimeServices intance
*/
public void init( RuntimeServices rsvc )
{
// do nothing
}
/**
* This is the method that you implement for Velocity to call
* with log messages.
*/
public void logVelocityMessage(int level, String message)
{
/* do something useful */
}
...
}
|
 |
 |
 |
 |
 |
 |
 |
 |
import org.apache.velocity.runtime.log.LogSystem;
...
public class MyClass implements LogSystem
{
...
public MyClass()
{
...
try
{
/*
* このクラスをロガーとして登録。
*/
Velocity.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM, this );
Velocity.init();
}
catch (Exception e)
{
/*
* 何か行ないます。
*/
}
}
/**
* この init() は、現在の RuntimeServices を用意するために、
* LogManager が一度だけ呼び出します。
*/
public void init( RuntimeServices rsvc )
{
// 何も行ないません。
}
/**
* Velocity がログメッセージを引数に呼び出すメソッドで、これを実装します。
*/
public void logVelocityMessage(int level, String message)
{
/* なにか意味のあることを行ないます */
}
...
}
|
 |
 |
 |
 |
|
|
|
Configuring Resource Loaders − リソースローダの設定
|
One of the fundamental and important parts about Velocity is the resource
management system and the resource loaders. They are referred to as 'resources'
here rather than 'templates' because the resource management system will also
handle non-template reasources, specifically things that are loaded via the
#include() directive.
Velocity で基本的かつ重要なものとして、
リソース管理システムとリソースローダがあげられます。管理対象が「テンプレート」
でなく、「リソース」となっているのは、リソース管理システムがテンプレート以外のリソース、
特に #include() 指示子によってロードされるようなものも扱っているからです。
The resource loader system if very flexible, allowing one or more resource
loaders to be in operation at the same time. This allows tremendous
flexibility in configuration and resource managment, and futher allows you
to write your own resource loaders for your special needs.
リソースローダシステムは非常に柔軟であり、複数のリソースローダを同時に
動作させられます。このおかげで設定やリソース管理が著しく柔軟になっていますし、
さらに、ユーザが特別な要件に基づく独自のリソースローダを書くことができます。
There are currently four kinds of resource loaders that are included with Velocity,
each described below. Note that in the example configuration properties given,
a common name for the loader is shown
(ex.'file' in file.resource.loader.path). This 'common name'
may not work for your configuration. Please read the section on
resource configuration properties
to understand how this system works. Also, each of these loaders is
located in the package org.apache.velocity.runtime.resource.loader.
現在、Velocity には以下で説明される4種類のリソースローダがあります。
注意: このサンプル設定プロパティでは、ローダの一般名が示されます(
例:「file」はfile.resource.loader.pathを指します)。
この「一般名」だと、あなたの設定では動かないかもしれません。
このシステムがどのように動作するかについて理解するには、
リソース設定プロパティに関するセクションを参照してください。
また、各ローダは org.apache.velocity.runtime.resource.loader
パッケージにあります。
-
FileResourceLoader : This loader gets resources from the filesystem. It's
configuration properties include :
-
file.resource.loader.path = <path to root of templates>
-
file.resource.loader.cache = true/false
-
file.resource.loader.modificationCheckInterval = <seconds between checks>
This is the default loader, and is configured, by default to get templates from the
'current directory'. In the case of using Velocity with servlets, this can be a problem
as you don't want to have to keep your templates in the directory from which you start
your servlet engine. Please see the section on
developing servlets with Velocity
for more information.
-
JarResourceLoader : This loader gets resource from specific jar files. It is very
similar to the FileResourceLoader, except that you have the convenience of bundling
your templates into jars. The properties are identical, except for
jar.resource.loader.path, where you provide the full location of
the jar(s) you wish to load resources from. To specify a jar for the loader.path
you use the standard JAR URL syntax of java.net.JarURLConnection.
-
ClasspathResourceLoader : This loader gets resources from the classloader.
In general, this means that the ClasspathResourceLoader will load
templates placed in the classpath (in jars, for example)
While the
classpath is a source of great pain and suffering in general, it is a very useful
mechanism when working on a Servlet Spec 2.2 (or newer) compliant servlet runner.
Tomcat
is an example of such. To use this loader effectively, all you must do is
jar your templates, and put that jar into the WEB-INF/lib directory of your
webapp. There are no configuration options to worry about, nor is the absolute vs.
relative path an issue, as it is with Jar and File resource loaders.
Again, please note that the ClasspathResourceLoader is not only for use with a
servlet container, but can be used in any application context.
-
DataSourceResourceLoader : This loader will load resources from a DataSource
such as a database. This loader is not built as part of the standard build
as it requires J2EE support. To build this loader, please download the J2EE
distribution, move the j2ee.jar into the
build/lib directory,
and then build the new velocity jar with the jar-j2ee build target.
For more information on this loader, please see the javadoc for the class
org.apache.velocity.runtime.resource.loader.DataSourceResourceLoader.
-
FileResourceLoader : このローダはファイルシステムからリソースを取得します。
設定プロパティは以下の通りです。
-
file.resource.loader.path = <テンプレートのルートパス>
-
file.resource.loader.cache = true/false
-
file.resource.loader.modificationCheckInterval = <チェック間隔 (秒) >
これはデフォルトのローダで、「カレントディレクトリ」からデフォルトでテンプレートを
取得する設定になっています。サーブレットで Velocity を使う場合、サーブレットエンジンを
起動するディレクトリにテンプレートを置きたくない時に、問題が発生する可能性があります。
詳細は Velocity でサーブレット開発のセクションを見てください。
-
JarResourceLoader :
このローダは、特定の JAR ファイルからリソースを取得します。
JAR ファイルにテンプレートをまとめられることを除いて、 FileResourceLoader
とほぼ同じです。プロパティについても、
jar.resource.loader.path 以外は
同じです。このプロパティでリソースをロードしたい JAR ファイル (複数可) のフルパスを
指定します。この loader.path で JAR ファイルを指定するには、 java.net.JarURLConnection の標準の JAR URL 構文を使います。
-
ClasspathResourceLoader :
このローダは、クラスローダからリソースを取得します。たいていの場合は、
ClasspathResourceLoader が、クラスパス内 (例えば、JARファイル内) のテンプレートを
ロードするということです。クラスパスは多くの場合大きな悩みの種ですが、
サーブレット仕様 2.2 以降に対応したサーブレットコンテナを動かす時には、
非常に役に立つ仕組みです。 Tomcat
は、こうしたサーブレットコンテナの一例です。このローダを効果的に使うには、
テンプレートを JAR ファイルに入れて、Webアプリの WEB-INF/lib ディレクトリに
置けば十分です。設定オプションを気にする必要はありませんし、JAR リソースローダや
File リソースローダで起こりうる絶対パス/相対パスの問題も起こりません。
繰り返しますが、ClasspathResourceLoader は、サーブレットコンテナだけでなく、
どのアプリケーションコンテキストでも使用できることに注意して下さい。
-
DataSourceResourceLoader :
このローダは、データベースなどの DataSource からリソースをロードします。
J2EE サポートが必要なので、標準ビルドでは、このローダはビルドされません。
このローダをビルドするためには、J2EE 配布をダウンロードし、 j2ee.jar を
build/lib ディレクトリに移動して、
jar-j2ee というビルドターゲットを使用して VelocityのJARファイルを
新たにビルドします。
このローダの詳細については、
org.apache.velocity.runtime.resource.loader.DataSourceResourceLoader
クラスの Javadoc をご覧下さい。
Configuration Examples
設定例
Configuring the resource loaders for Velocity is straightforward.
The properties that control the are listed in the
resource configuration
section, for further reference.
Velocity でのリソースローダの設定は簡単です。
さらに詳細を知りたい場合は、
リソース設定
セクションにある、制御のためのプロパティの一覧を参照してください。
The first step in configuring one or more resource loaders is do
'declare' them by name to Velocity. Use the property
resource.loader and list one or more loader names.
You can use anything you want - these names are used to associate
configuration properties with a given loader.
一つ以上のリソースローダを設定する場合、最初のステップとして
Velocity に対してリソースローダを名前で「宣言」します。
プロパティ resource.loader を使い、一つ以上のローダ名を
[コンマ区切りの]リストで指定します。どんな名前でもかまいません ──
これらの名前は、該当するローダを設定プロパティに関連づけるために使われます。
That entry declares that we will have a resource loader known as 'file'.
The next thing to do is to set the important properties. The most critical
is to declare the class to use as the loader :
このエントリでは、「file」として知られているリソースローダを
使うと宣言しています。次に行なうのは、重要なプロパティをセットすることです。
ここで一番大事なのは、ローダとして使用するクラスを宣言することです。
 |
 |
 |
 |
file.resource.loader.class = org.apache.velocity.runtime.resource.loader.FileResourceLoader
|
 |
 |
 |
 |
In this case, we are telling velocity that we are setting up
a resource loadercalled 'file', and are using the class
org.apache.velocity.runtime.resource.loader.FileResourceLoader
to be the class to use.
The next thing we do is set the properties important
to this loader.
この場合、「file」というリソースローダを設定し、それが
org.apache.velocity.runtime.resource.loader.FileResourceLoader
クラスを使用することを Velocity に伝えます。
次に、このローダにとって重要なプロパティを設定します。
 |
 |
 |
 |
file.resource.loader.path = /opt/templates
file.resource.loader.cache = true
file.resource.loader.modificationCheckInterval = 2
|
 |
 |
 |
 |
Here, we set a few things. First, we set the path to find
the templates to be /opt/templates. Second, we
turned caching on, so that after a template or static file
is read in, it is cached in memory. And finally, we set
the modification check interval to 2 seconds, allowing Velocity
to check for new templates.
ここで3つの設定を行っています。ます、テンプレートを見つけるためのパスとして
/opt/templates を設定しています。次に、テンプレートまたは静的ファイルが
読まれた後、メモリにキャッシュされるように、キャッシュをオンにしています。
最後に、新しいテンプレートの更新チェック間隔を2秒にセットしています。
Those are the basics. What follows are a few examples of different configuraitons.
基本的な設定は以上です。他の設定例もいくつか挙げましょう。
Do-nothing Default Configuration : As the name says, there is nothing
you have to do or configure to get the default configuration. This configuration
uses the FileResourceLoader with the current directory as the default resource
path, and caching is off. As a properties set, this is expressed as :
何もしないデフォルト設定 :
その名のとおり、デフォルト設定を取得するのに何もする必要はありません。
この設定ではデフォルトのリソースパスとしてカレントディレクトリで FileResourceLoader を
使い、キャッシュはオフです。プロパティは以下のようになります。
 |
 |
 |
 |
resource.loader = file
file.resource.loader.description = Velocity File Resource Loader
file.resource.loader.class = org.apache.velocity.runtime.resource.loader.FileResourceLoader
file.resource.loader.path = .
file.resource.loader.cache = false
file.resource.loader.modificationCheckInterval = 0
|
 |
 |
 |
 |
Multiple Template Path Configuration : This configuration
uses the FileResourceLoader with several directories as 'nodes' on the
template search path. We also want to use caching, and have the templates
checked for changes in 10 second intervals. As a properties set, this is expressed as :
複数テンプレートパス設定 :
テンプレートの検索パスの「ノード」として複数のディレクトリが指定された
FileResourceLoader を使用するように設定します。また、キャッシュを使い、
テンプレートの変更を10秒間隔でチェックします。プロパティは以下のようになります。
 |
 |
 |
 |
resource.loader = file
file.resource.loader.description = Velocity File Resource Loader
file.resource.loader.class = org.apache.velocity.runtime.resource.loader.FileResourceLoader
file.resource.loader.path = /opt/directory1, /opt/directory2
file.resource.loader.cache = true
file.resource.loader.modificationCheckInterval = 10
|
 |
 |
 |
 |
Multiple Loader Configuration : This configuration sets up
three loaders at the same time, the FileResourceLoader,
the ClasspathResourceLoader, and the JarResourceLoader.
The loaders are set-up such that the
FileResourceLoader is consulted first, then the
ClasspathResourceLoader, and finally the JarResourceLoader.
This would allow you to qickly
drop a template into the file template area to replace on of the
templates found in the classpath (usually via a jar) without
having to rebuild the jar.
複数ローダ設定 :
この設定は、FileResourceLoader、ClasspathResourceLoader、JarResourceLoader という
3つのローダを同時に動かすようにセットアップします。
ローダは、最初に FileResourceLoader、次に ClasspathResourceLoader、
最後に JarResourceLoader が参照されます。こうすれば、クラスパス上にあるテンプレートを
置き換える際に、ファイルテンプレートの領域に入れるだけでよく、JAR ファイルを
再ビルドする必要はありません。
 |
 |
 |
 |
#
# specify three resource loaders to use
#
resource.loader = file, class, jar
#
# for the loader we call 'file', set the FileResourceLoader as the
# class to use, turn off caching, and use 3 directories for templates
#
file.resource.loader.description = Velocity File Resource Loader
file.resource.loader.class = org.apache.velocity.runtime.resource.loader.FileResourceLoader
file.resource.loader.path = templatedirectory1, anotherdirectory, foo/bar
file.resource.loader.cache = false
file.resource.loader.modificationCheckInterval = 0
#
# for the loader we call 'class', use the ClasspathResourceLoader
#
class.resource.loader.description = Velocity Classpath Resource Loader
class.resource.loader.class = org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
#
# and finally, for the loader we call 'jar', use the JarResourceLoader
# and specify two jars to load from
#
jar.resource.loader.description = Velocity Jar Resource Loader
jar.resource.loader.class = org.apache.velocity.runtime.resource.loader.JarResourceLoader
jar.resource.loader.path = jar:file:/myjarplace/myjar.jar, jar:file:/myjarplace/myjar2.jar
|
 |
 |
 |
 |
 |
 |
 |
 |
#
# 使用する3つのリソースローダを指定
#
resource.loader = file, class, jar
#
# 'file'と名づけたローダでは、使用するクラスとして FileResourceLoader をセットして
# キャッシュを off にして、 テンプレート用に3つのディレクトリを使用する
#
file.resource.loader.description = Velocity File Resource Loader
file.resource.loader.class = org.apache.velocity.runtime.resource.loader.FileResourceLoader
file.resource.loader.path = templatedirectory1, anotherdirectory, foo/bar
file.resource.loader.cache = false
file.resource.loader.modificationCheckInterval = 0
#
# 'class'と名づけたローダでは、ClasspathResourceLoader を使用する
#
class.resource.loader.description = Velocity Classpath Resource Loader
class.resource.loader.class = org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
#
# 最後に、'jar'と名づけたローダでは、JarResourceLoader を使用し、
# 2つの JAR ファイルから読み込む
#
jar.resource.loader.description = Velocity Jar Resource Loader
jar.resource.loader.class = org.apache.velocity.runtime.resource.loader.JarResourceLoader
jar.resource.loader.path = jar:file:/myjarplace/myjar.jar, jar:file:/myjarplace/myjar2.jar
|
 |
 |
 |
 |
Node that the three names 'file', 'class', and 'jar' are merely for your convenience and
sanity. They can be anything you want - they are just used to associate a set of
properties together. However, it is recommended that you use names that give some hint
of the function.
「file」、「class」、「jar」という名前はあくまで都合と分類のためのものであることに
注意してください。これらは好きな名前でかまいません ─ プロパティと関連づけるために、
使われるだけだからです。とはいえ、機能のヒントとなる名前を使用することをお勧めします。
Note that while all three require very little configuration information
for proper operation, the ClasspathResourceLoader is the simplest.
適切に動作させるのに必要な設定情報は3つともごくわずかですが、
ClasspathResourceLoader はその中でも最も単純です。
Pluggable Resource Manager and Resource Cache
プラグイン可能なリソースマネージャとリソースキャッシュ
The Resource Manager is the main part of the resource (template and static content)
management system, and is responsible for taking application requests for
templates, finding them in the available resource loaders, and then optionally
caching the parsed template. The Resource Cache is the mechanism that the
Resource Manager uses to cache templates for quick reuse. While the default
versions of these two facilities are suitable for most
applications, for advanced users it now is possible
to replace the default resource manager
and resource cache with custom implementations.
リソースマネージャはリソース (テンプレートと静的コンテンツ)
の主要部分を管理するシステムで、テンプレートへのアプリケーションのリクエストを受け取り、
利用可能なリソースローダでそれらを見つけ、
オプションとしてパース済みのテンプレートのキャッシュを行ないます。
リソースキャッシュとは、リソースマネージャがテンプレートの再利用を高速に行なえるように、
テンプレートをキャッシュする仕組みです。ほとんどのアプリケーションの場合、
こうした2つの機能のデフォルトのバージョンで十分ですが、
上級ユーザなら、デフォルトのリソースマネージャとリソースキャッシュを、
カスタム実装に置き換えることも可能です。
A resource manager implementation must implement the
org.apache.velocity.runtime.resource.ResourceManager interface.
A description of the requirements of a resource manager is out of scope for
this document. Implementors are encouraged to review the default implementation.
To configure Velocity to load the replacement implementation, use the
configuration key :
リソースマネージャの実装時には、
org.apache.velocity.runtime.resource.ResourceManager
インタフェースを実装しなければなりません。
リソースマネージャの要件記述についてはこの文書の範囲外となります。
実装する人はデフォルトの実装をチェックすることをお勧めします。
Velocity で代わりの実装をロードするには、以下の設定キーを使います。
This key is also defined as a contstant
RuntimeConstants.RESOURCE_MANAGER_CLASS
このキーはまた、RuntimeConstants.RESOURCE_MANAGER_CLASS
という定数としても定義されています。
|
|
|
Template Encoding for Internationalization − 国際化のためのテンプレートエンコーディング
|
As of version 1.1, Velocity allows you to specify the character encoding of your
template resources on a template by template basis. The normal resource
API's have been extended to take the encoding as an argument :
バージョン1.1現在、テンプレートごとにテンプレートリソースの文字エンコーディングを
指定できます。通常のリソース API は、エンコーディングを引数として渡せるように
拡張されています。
org.apache.velocity.servlet.VelocityServlet :
public Template getTemplate( String template, String encoding )
org.apache.velocity.app.Velocity :
public static Template getTemplate(String name, String encoding)
public static boolean mergeTemplate( String templateName, String encoding, Context context, Writer writer )
The value for the encoding argument is the conventional encoding specification
supported by your JVM, for example "UTF-8" or "ISO-8859-1". For the official names
for character sets, see here.
encoding引数の値は JVM でサポートされる通常のエンコーディング仕様
(例:「UTF-8」、「ISO-8859-1」) です。
文字セットの公式名称は、
こちらを参照してください。
Note that this applies only to the encoding of the template itself - the output
encoding is an application specific issue.
注意:これはテンプレート自身のエンコーディングにのみ適用されます ──
出力エンコーディングはアプリケーション固有の問題です。
|
|
|
Velocity and XML − Velocity と XML
|
Velocity's flexibility and simple template language makes it an ideal environment
for working with XML data. Anakia is an example of how
Velocity is used to replace XSL for rendering output from XML. The Velocity site,
including this documentation, is generated from XML source using Anakia.
The Jakarta site is also rendered using Anakia.
Velocity は柔軟で単純なテンプレート言語であるため、 XML データを利用するのに
理想的な環境となっています。Anakia は、
XML からの出力処理で XSL を置き換えるのに Velocity を利用する例です。
このドキュメンテーションを含む Velocity サイトは、Anakia を使って、
XML ソースから生成しています。 Jakarta サイトもまた Anakia を使用して処理されています。
Generally, the pattern for dealing with XML in Velocity is to use something like
JDOM to process your XML into a data structure with
convenient Java access. Then, you produce templates that access data directly
out of the XML document - directly though the JDOM tree. For example, start
with an XML document such as :
Velocity で XML を扱うパターンとしては、XML を Java
アクセスしやすいデータ構造に変換できる
JDOM などを使うのが一般的です。
その場合、XML ドキュメントから (JDOM ツリー経由で)
直接データアクセスするテンプレートを生成します。
例として、次の XML 文書を使ってみましょう。
 |
 |
 |
 |
<?xml version="1.0"?>
<document>
<properties>
<title>Developer's Guide</title>
<author email="geirm@apache.org">Velocity Documentation Team</author>
</properties>
</document>
|
 |
 |
 |
 |
Now make a little Java program that includes code similar to:
ここで、以下のようなコードを含む小さな Java プログラムを作成します。
 |
 |
 |
 |
...
SAXBuilder builder;
Document root = null;
try
{
builder = new SAXBuilder( "org.apache.xerces.parsers.SAXParser" );
root = builder.build("test.xml");
}
catch( Exception ee)
{}
VelocityContext vc = new VelocityContext();
vc.put("root", root );
...
|
 |
 |
 |
 |
(See the Anakia source for details on how to do this, or the Anakia
example in the examples directory in the distribution.)
Now, make a regular Velocity template :
(このやり方についての詳細は、配布のexamplesディレクトリにある
Anakia サンプルを参照してください。)
次に、通常の Velocity テンプレートを作成します。
 |
 |
 |
 |
<html>
<body>
The document title is
$root.getChild("document").getChild("properties").getChild("title").getText()
</body>
</html>
|
 |
 |
 |
 |
and render that template as you normally would, using the Context
containing the JDOM tree. Of course, this isn't the prettiest of
examples, but it shows the basics - that you can easily access XML data
directly from a Velocity template.
そして、JDOM ツリーを含む Context を使って、
いつものようにテンプレートを処理します。
もちろん、この例がすべてではありませんが、 Velocity テンプレートから簡単に XMLデータに
直接アクセスする基本的な方法を示しています。
One real advantage of styling XML data in Velocity is that you have
access to any other object or data that the application provides. You
aren't limited to just using the data present in the XML document.
You may add anything you want to the context to provide additional
information for your output, or provide tools to help make working
with the XML data easier. Bob McWhirter's
Werken Xpath
is one such useful tool - an example of how it is used in Anakia can be
found in org.apache.velocity.anakia.XPathTool.
Velocity で XML データを整形する大きな利点の一つは、
アプリケーションが用意する他のオブジェクトやデータにアクセスできるということです。
その XML 文書にあるデータが使えるだけではありません。
出力に関する追加情報を提供するためにコンテキストに何でも追加できますし、
XML データを使いやすくするツールも提供できます。
Bob McWhirter の
Werken Xpath
はこの種の便利なツールの一つです ─ Anakia での使い方の例は
org.apache.velocity.anakia.XPathTool にあります。
One issue that arises with XML and Velocity is how to deal with XML
entities. One technique is to combine the use of Velocimacros
when you need to render an entity into the output stream :
XML と Velocity で起こる問題の1つに、XML エンティティをどう扱うかというものがあります。
テクニックの一つとして、エンティティを処理して出力ストリームに送る際に、
Velocimacro と組み合わせて使うという方法があります。
 |
 |
 |
 |
## first, define the Velocimacro somewhere
#macro( xenc $sometext )$tools.escapeEntities($sometext)#end
## and use it as
#set( $sometext = " < " )
<text>#xenc($sometext)</text>
|
 |
 |
 |
 |
 |
 |
 |
 |
## まず、Velocimacro をどこかで定義します
#macro( xenc $sometext )$tools.escapeEntities($sometext)#end
## そして以下のように使用します
#set( $sometext = " < " )
<text>#xenc($sometext)</text>
|
 |
 |
 |
 |
where the escapeEntities() is a method that does the escaping
for you. Another trick would be to create an encoding utility that takes the
context as a constructor parameter and only implements a method:
この例で escapeEntities() メソッドはエスケープを行ないます。
コンストラクタの引数でコンテキストを取得し、
以下のメソッドだけを実装するエンコードユーティリティを作成するという手もあります。
 |
 |
 |
 |
public String get(String key)
{
Object obj = context.get(key)
return (obj != null) ? Escape.getText( obj.toString() ) : "";
}
|
 |
 |
 |
 |
Put it into the context as "xenc". Then you can use it as :
コンテキストには "xenc" というキーで設定します。そして以下のように使用します。
 |
 |
 |
 |
<text>$xenc.sometext</text>
|
 |
 |
 |
 |
This takes advantage of Velocity's introspection process - it will try
to call get("sometext") on the $xenc object in the Context - then the
xenc object can then get the value from the Context, encode it, and
return it.
この方法だと Velocity のイントロスペクション プロセスが使えるという利点があります ─
このコードではコンテキスト内の $xenc オブジェクトの get("sometext") を呼び出そうと
します ─ そして xenc オブジェクトは、Context から値を取得、エンコードして返すことが
できます。
Alternatively, since Velocity makes it easy to implement custom Context
objects, you could implement your own context which always applies the
encoding to any string returned. Be careful to avoid rendering the
output of method calls directly, as they could return objects or strings
(which might need encoding). Place them first into the context with a
#set() directive and the use that, for example :
別の方法として、
Velocity がカスタムのコンテキストオブジェクトを簡単に実装できることを利用して、
返り値の文字列すべてにエンコーディングを常に適用する独自のコンテキストを実装するというのも「あり」でしょう。
その場合、メソッド呼び出しの出力は直接処理しないように気をつけてください。
メソッド呼び出しでは (エンコーディングが必要かもしれない)
オブジェクトや文字列を返す可能性があるからです。
#set() 指示子でコンテキストに設定してから使うようにしましょう。
以下に例を挙げます。
 |
 |
 |
 |
#set( $sometext = $jdomElement.getText() )
<text>$sometext</text>
|
 |
 |
 |
 |
The previous suggestions for dealing with XML entities came from
Christoph Reck, an active participant in the Velocity community. We are
very grateful for his [unknowing] contribution to this document, and
hope his ideas weren't mangled too badly :)
XML エンティティを扱う前者の方法は、Christoph Reck
(Velocityコミュニティへのアクティブな参加者です) のアイデアを元にしています。
この文書への彼の (知られざる) 貢献に、非常に感謝しています。
彼のアイデアはそれほどめちゃめちゃにはなってないと思います :)
|
|
|
FAQ (Frequently Asked Questions) − FAQ (よく聞かれる質問)
|
In no apparent order, here are questions and answers that repeatedly arise
by developers using Velocity. As we get more, we will move this out to
a separate document.
Velocity を使う開発者から繰り返し上がってくる質問とその回答を紹介します (順不同) 。
もしさらに増えるようでしたら、別の文書にしようと思います。
Why Can't I Access Class Members and Constants from VTL?
VTL のクラスメンバやコンスタントにアクセスできないんだけど、どうして?
The short answer is because we don't introspect for fields. We don't do that
because we wish to promote the idea that you hide your raw data in your
data objects. There are two solutions to this issue. The first is
that you should be writing accessors for data elements you wish to be
publicly exposed. That of course won't work for instances where you don't
have the source, or simply are too lazy. There is a class for the latter
group, org.apache.velocity.app.FieldMethodizer which introspects
your class, and exposes the public static fields in a way that allows easy
access from a template. Suppose you have a class :
簡単に言えば、フィールドについてはイントロスペクションを行っていないからです。
その理由はデータオブジェクトの生のデータは隠すという考え方を推進したいからです。
この問題の解決法は2通りあります。
一つは公開したいデータ要素へのアクセッサを書くことです。
もちろん、この方法はソースが入手できない場合は使えませんし、
単に面倒くさいという場合も同様です。
もう一つの解決法のために、クラスをイントロスペクションして、
テンプレートから簡単にアクセスできるようにパブリックで静的なフィールドを公開する
org.apache.velocity.app.FieldMethodizer というクラスがあります。
例えばこんなクラスがあるとしましょう。
 |
 |
 |
 |
public class Foo
{
public static String PATH_ROOT = "/foo/bar";
....
}
|
 |
 |
 |
 |
Then, in your code, you would put a Foo into the context like this
これを利用するコードで Foo を以下のようにコンテキストに設定します。
 |
 |
 |
 |
context.put("myfoo", new FieldMethodizer( new Foo() ) );
|
 |
 |
 |
 |
Then to access this field in your template, you would simply access in
a manner similar to Java :
テンプレートでこのフィールドにアクセスするには、Java と同じやり方で
簡単にアクセスできます。
If you have a crushing need to access public non-static members (or even private
if you are so driven), then you would have to exend / modify the
FieldMethodizer yourself. (And we still recommend you provide accessors....)
もし、パブリックで静的でないメンバにアクセスせざるを得ない壊滅的な状況
(あるいは、プライベートメンバにアクセスしなければならないような破滅間際の状況)
なら、FieldMethodizer クラスを自分で継承あるいは修正する必要が
あります。(もちろん、それでもなおアクセッサを用意することをお勧めしますが……)
Where does Velocity look for Templates?
Velocity はテンプレートをどこで探すの?
By default, without any configuration on your part, Velocity will look
for templates in files, and look for them in the current directory
(or relative to the current directory, if you prepend a path to your
template, like 'foo/bar.vm').
デフォルト、つまり何も自分で設定していない場合は、Velocity は
カレントディレクトリ (あるいは「foo/bar.vm」のようにテンプレート
へのパスを設定している場合はカレントディレクトリ基準の相対パス)
にあるファイルをテンプレートとして探します。
Velocity does this to make it as easy as possible to use out of the box.
It has been argued that Velocity should do it from the 'root' directory, but
it's never clear what that is on filesystems where there are multiple roots
(like - "C:\", "D:\", etc).
Velocity でそのようにしているのは、インストール直後でもできるだけそのまま使える
ようにするためです。「ルート」ディレクトリから探すべきだという意見もありましたが、
その場合、複数のルートを持つ (「C:\」「D:\」……のように) ファイルシステムでの
対応方法がはっきりしていません。 [そのため採用していません。]
For more information, see the section on
resource loaders as well as the section on
configuration keys, values and defaults.
詳細については、
リソースローダに関するセクションや、
設定キー、値、デフォルト値に関するセクションを見てください。
|
|
|
Summary − まとめ
|
We hope this brief guide was a helpful introduction to using Velocity in
your Java projects, and thank you for you interest in Velocity. We
welcome any and all comments you may have about this documentation and
the Velocity template engine itself.
簡素なガイドではありますが、Java のプロジェクトで Velocity
を使うための概論としてお役に立てたなら幸いです。
また、Velocity に興味をもっていただいたことを感謝しています。
このドキュメンテーションについて、あるいは Velocity
テンプレートエンジンそのものに関するコメントは何でも歓迎します。
Please submit all detailed, thoughtful and constructive feedback through our
mail lists.
フィードバックをしていただくには、
メーリングリスト
に参加していただく必要があります。また、よく考えた上で、詳細かつ建設的な内容で
お願いします。
|
|
|
Appendix 1 : Deploying the Example Servlet − 追記1:サンプルサーブレットの配備
|
A continuing source of frustration for beginning servlet users is getting
all the pieces into place and working. Using a servlet engine like Tomcat or Resin
is far from obvious for the first time user (and even for more experienced users...).
The following are the basic instructions, to the best of our knowledge, for getting
the SampleServlet example working. Note that the sample template sample.vm
and the servlet code itself, SampleServlet.java are
found in the examples/servlet_example directory. Although some servlet
engines (Resin, for example) will compile the servlet for you, it would be best if
you compiled the examples first. To do this, see the section on building Velocity, and
use the examples target.
初心者のサーブレットユーザが挫折することが多いのは、全てをまとめた上で動かす時です。
Tomcat や Resin といったサーブレットエンジンの使い方は初めて使う人には分かりづらいのです
(そして、慣れたユーザでさえも……)。
SampleServlet サンプルを動かすための基本的な手順を以下で説明します
(できるだけ分かりやすくしたつもりです)。注意事項として、
サンプルテンプレートである sample.vm と、
サーブレットコードそのものである SampleServlet.java は、
examples/servlet_example ディレクトリにあります。
サーブレットエンジンによっては(例えば Resin など)、
サーブレットを自動的にコンパイルしてくれますが、
動かす前にサンプルをコンパイルするに越したことはないでしょう。
コンパイルする方法については、
Velocity のビルドに関する説明
を見ていただいた上で、 examples をお使い下さい。
Jakarta Tomcat
Jakarta Tomcat
Setting up under Jakarta Tomcat is fairly
straightforward. The 'webapp' directory is where Tomcat automatically
looks for it's 'web applications', so
this is where we will set things up.
Jakarta Tomcat
での設定はわりと簡単です。Tomcat は「webapps」ディレクトリで
「Web アプリ」を探すので、そこでセットアップすればいいのです。
- First, make a new 'webapp' by creating a directory called velexample
in Tomcat's webapps directory, and make
a new directory structure as follows :
velexample
velexample/WEB-INF
velexample/WEB-INF/lib
velexample/WEB-INF/classes
-
Put the Velocity jar into the velexample/WEB-INF/lib directory. Note that with v1.2
and newer, you either have to either use the jar from the distribution (or that you
build yourself) that contains all the dependencies ( ex. velocity-dep-1.2.jar) or
you must add the dependency jars yourself to the WEB-INF/lib directory. Please see
the section "Getting Started" and "Dependencies", above.
-
Put the SampleServlet.class into the velexample/WEB-INF/classes directory
-
Put the sample.vm template into the velexample directory. The SampleServlet is
written to use the root of the webapp as the source of the templates, so
no configuration is needed.
-
At this point, you should be able to start (or restart) Tomcat and access the servlet.
-
To access the servlet, point your web browser at :
http://localhost:8080/velexample/servlet/SampleServlet
or if that doesn't work :
http://<your computer's ip address>:8080/velexample/servlet/SampleServlet
-
You should see the sample output.
- まず、Tomcat の webapps ディレクトリに velexample
という名前でディレクトリを作成して新しい「Web アプリ」を作り、
以下のようなディレクトリ構造にします。
velexample
velexample/WEB-INF
velexample/WEB-INF/lib
velexample/WEB-INF/classes
-
velocity-1.2.jar を velexample/WEB-INF/lib ディレクトリに置きます。バージョン 1.2
以降では、(velocity-dep-1.2.jar のような) 全ての依存ライブラリを含む配布の
JAR ファイル (自分でビルドしたものも含む)を使うか、WEB-INF/lib ディレクトリに、
依存する JAR ファイルを自分で追加する必要があります。詳しくは先述の
「導入」および「依存関係」
をご覧下さい。
-
SampleServlet.class を velexample/WEB-INF/classes ディレクトリに置きます。
-
sample.vm テンプレートを velexample ディレクトリに置きます。SampleServlet は、
テンプレートのソースディレクトリとして Web アプリのルートディレクトリを使うので、
それ以外の設定は不要です。
-
これで Tomcat を起動(または再起動)すればサーブレットにアクセスできるはずです。
-
サーブレットにアクセスするには、Web ブラウザで以下のアドレスを指定します。
http://localhost:8080/velexample/servlet/SampleServlet
もし、うまく動かなければ、以下のアドレスを指定してみてください。
http://<あなたのコンピュータのIPアドレス>:8080/velexample/servlet/SampleServlet
[訳注: Tomcat 4.1以降ではセキュリティの観点から、
このアドレス指定方法では動作しないようになったため、
Web アプリの web.xml でサーブレットの設定をした上で、
別のアドレス指定をする必要があります。
詳しくは Tomcat のドキュメントをご覧下さい。]
-
サンプル出力が表示されるはずです。
Caucho Technology's Resin
Caucho Technology の Resin
Setting up the example servlet under Caucho Technology's Resin
servlet engine is also very simple. The following instructions were tested with the version 1.2.5
release. The following assume that you have unzip-ed or untar-ed the distribution, know how to start
the servlet engine (something like bin/httpd.sh under unix...), and know where the doc directory is
(in the root of the distribution).
Caucho Technology の Resin
サーブレットエンジンでサンプルサーブレットを動かすのもとても簡単です。
以下の手順はVersion 1.2.5リリースでテストしました。
すでに、ディストリビューションを ZIP か TAR で解凍済みで、
サーブレットエンジンの起動方法(Unix なら bin/httpd.sh とか)がわかっており、
doc ディレクトリ(ディストリビューションのルート)がどこにあるか
わかっていることを前提にしています。
-
Copy the SampleServlet.class file into the doc/WEB-INF/classes directory.
-
Copy the sample.vm template file into the doc/ directory
-
Copy the Velocity jar (and any required dependencies - see note above in
Tomcat setup section) into the doc/WEB-INF/lib directory.
-
Start resin.
-
To access the servlet, point your web browser at :
http://localhost:8080/servlet/SampleServlet
or if that doesn't work :
http://<your computer's ip address>:8080/servlet/SampleServlet
and you should see the output.
-
SampleServlet.class ファイルを doc/WEB-INF/classes ディレクトリにコピーします。
-
sample.vm テンプレートファイルを doc/ ディレクトリにコピーします。
-
Velocity の Jar ファイル (および必要な依存ライブラリ ─ 詳しくは Tomcat
のセットアップのセクションをご覧下さい) を doc/WEB-INF/lib ディレクトリにコピーします。
-
Resin を起動します。
-
サーブレットにアクセスするには、Web ブラウザで以下のアドレスを指定します。
http://localhost:8080/servlet/SampleServlet
もし、うまく動かなければ、以下のアドレスを指定してみてください。
http://<あなたのコンピュータのIPアドレス>:8080/servlet/SampleServlet
サンプル出力が表示されるはずです。
Note that this appeared to be a simpler configuration - with the Tomcat example,
you set up a complete, new, separate webapp, whereas the Resin instructions
don't, although both should provide a sufficient setup to let you play with
Velocity.
こちらの方が設定が単純なように見えます -- Tomcat サンプルの場合は
別々の完全な Web アプリを新たに設定するのに対して、Resinの場合はその必要が
ないからです-- しかし、どちらの場合も Velocity と一緒に動かすためには十分な設定が
必要であることに注意して下さい。
Note that while we wish we could, we can't answer questions about the servlet
engines. Please use the resources provided by the servlet engine provider.
注意:残念ながら、サーブレットエンジンに関するご質問にはお答えできません。
サーブレットエンジンの提供元にお問い合わせ下さい。
BEA WebLogic
BEA WebLogic
Paw Dybdahl <pdy@csg.csc.dk> contributed this
description of using Velocity with WebLogic, as well as some good general suggestions and
examples for working with servlets.
Paw Dybdahl <pdy@csg.csc.dk> が、WebLogic での Velocity の使い方や、
サーブレットと一緒に使う場合の一般的なアドバイスを、
ここで行っています。
|
|
|