LittleSoft J-Programming
3.1. HTML テンプレートの表示
この章では、HTML 画面の雛型(テンプレート)に ActionPage の値を埋め込み、HTML 画面を出力する手順について説明します。

ActionPage クラスを作成する
LSJ 基底クラス「 ActionPage 」を継承し、ActionPage クラス「 WelcomePage 」を作成します。
/* WelcomePage クラス */
public class WelcomePage extends ActionPage {
/* コンストラクタ */
public WelcomePage(HttpServletRequest request,
HttpServletResponse response) throws Exception {
super(request, response);
}
}
public class WelcomePage extends ActionPage {
/* コンストラクタ */
public WelcomePage(HttpServletRequest request,
HttpServletResponse response) throws Exception {
super(request, response);
}
}
テンプレートに埋め込む変数を宣言する
「 public 」宣言することにより、テンプレートからのアクセスが可能になります。
/* 現在時刻 */
public Date now = null;
public Date now = null;
変数に値を設定する
宣言した変数に値を設定します。
/* コンストラクタ */
public WelcomePage(HttpServletRequest request,
HttpServletResponse response) throws Exception {
super(request, response);
// 現在時刻を設定
now = new java.util.Date();
}
public WelcomePage(HttpServletRequest request,
HttpServletResponse response) throws Exception {
super(request, response);
// 現在時刻を設定
now = new java.util.Date();
}
表示する HTML テンプレートを指定する
「 setTemplateName 」メソッドを使用し、表示するテンプレートを指定します。
※Velocity のファイル検索パスのデフォルトは「 WEB コンテキストのルート 」です。 サンプルアプリでは web.xml にて、読み込みパスを「 WEB コンテキストのルート / template 」としています。
/* コンストラクタ */
public WelcomePage(HttpServletRequest request,
HttpServletResponse response) throws Exception {
super(request, response);
// 現在時刻を設定
now = new java.util.Date();
// 表示するテンプレートを設定
setTemplateName("WelcomePage.html");
}
public WelcomePage(HttpServletRequest request,
HttpServletResponse response) throws Exception {
super(request, response);
// 現在時刻を設定
now = new java.util.Date();
// 表示するテンプレートを設定
setTemplateName("WelcomePage.html");
}
テンプレートファイル名の指定
Velocity のファイル検索パスからの相対パスで記述します。※Velocity のファイル検索パスのデフォルトは「 WEB コンテキストのルート 」です。 サンプルアプリでは web.xml にて、読み込みパスを「 WEB コンテキストのルート / template 」としています。
HTML テンプレートを作成し、変数を埋め込む
HTML ファイルを作成し、ActionPage で宣言した変数名に「 $ 」を付与して記述します。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>ようこそ画面</title>
</head>
<body>
ようこそ!現在 $now です。
</body>
</html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>ようこそ画面</title>
</head>
<body>
ようこそ!現在 $now です。
</body>
</html>
ページを表示する
ようこそ画面に、現在の時刻が表示されていることを確認します。
