Jsf-quick-guide
JSF-概要
JSFとは
*JavaServer Faces* (JSF)は、ページ内の再利用可能なUIコンポーネントを使用して、サーバーベースのアプリケーションのユーザーインターフェイス(UI)の構築を簡素化するMVC Webフレームワークです。 JSFは、UIウィジェットをデータソースとサーバー側イベントハンドラーに接続する機能を提供します。 JSF仕様は、標準UIコンポーネントのセットを定義し、コンポーネントを開発するためのApplication Programming Interface(API)を提供します。 JSFは、既存の標準UIコンポーネントの再利用と拡張を可能にします。
利点
JSFは、Javaアプリケーションサーバーで実行され、アプリケーションUIをターゲットクライアントにレンダリングするアプリケーションの作成と保守の労力を削減します。 JSFは、以下によってWebアプリケーション開発を促進します-
- 再利用可能なUIコンポーネントの提供
- UIコンポーネント間のデータ転送を簡単にする
- 複数のサーバー要求にわたるUI状態の管理
- カスタムコンポーネントの実装を有効にする
- クライアント側イベントをサーバー側アプリケーションコードに結び付ける
JSF UIコンポーネントモデル
JSFは、複数のクライアントタイプ(HTMLブラウザー、ワイヤレス、WAPデバイスなど)に対してさまざまな方法でレンダリングできるUIコンポーネントのコレクションからWebアプリケーションを作成する機能を開発者に提供します。
JSFが提供するもの-
- コアライブラリ
- 基本UIコンポーネントのセット-標準HTML入力要素
- 追加のUIコンポーネントライブラリを作成したり、既存のコンポーネントを拡張したりするためのベースUIコンポーネントの拡張
- JSF UIコンポーネントがクライアントタイプに応じて異なるレンダリングを可能にする複数のレンダリング機能
JSF-環境設定
この章では、JSFフレームワークで作業を開始するための開発環境を準備する方法について説明します。 JSFフレームワークをセットアップする前に、マシンでJDK、Eclipse、Maven、およびTomcatをセットアップする方法を学習します。
システム要件
JSFはJDK 1.5以降を必要とするため、最初の要件はJDKをマシンにインストールすることです。
JDK | 1.5 or above |
Memory | No minimum requirement |
Disk Space | No minimum requirement |
Operating System | No minimum requirement |
JSFアプリケーション開発の環境設定
指定された手順に従って環境をセットアップし、JSFアプリケーション開発を開始します。
ステップ1:マシンでのJavaインストールの検証
コンソールを開き、次の Java コマンドを実行します。
OS | Task | Command |
---|---|---|
Windows | Open Command Console | c:\> java -version |
Linux | Open Command Terminal | $ java -version |
Mac | Open Terminal | machine:~ joseph$ java -version |
すべてのオペレーティングシステムの出力を確認しましょう-
OS | Generated Output |
---|---|
Windows |
java version "1.6.0_21" Java(TM)SEランタイム環境(ビルド1.6.0_21-b07) Java HotSpot(TM)Client VM(ビルド17.0-b17、混合モード、共有) |
Linux |
java version "1.6.0_21" Java(TM)SEランタイム環境(ビルド1.6.0_21-b07) Java HotSpot(TM)Client VM(ビルド17.0-b17、混合モード、共有) |
Mac |
java version "1.6.0_21" Java(TM)SEランタイム環境(ビルド1.6.0_21-b07) Java HotSpot(TM)64ビットサーバーVM(ビルド17.0-b17、混合モード、共有) |
ステップ2:Java Development Kit(JDK)をセットアップする
Javaがインストールされていない場合は、OracleのJavaサイト(https://www.oracle.com/technetwork/java/javase/downloads/indexl[Java SEダウンロード])からJavaソフトウェア開発キット(SDK)をインストールできます。 ダウンロードしたファイルにJDKをインストールする手順があります。指定された手順に従ってセットアップをインストールおよび構成します。 最後に、PATHおよびJAVA_HOME環境変数を設定して、javaおよびjavacを含むディレクトリ、通常はそれぞれjava_install_dir/binおよびjava_install_dirを参照します。
*JAVA_HOME* 環境変数を設定して、Javaがマシンにインストールされているベースディレクトリの場所を指すようにします。
たとえば-
OS | Output |
---|---|
Windows | Set the environment variable JAVA_HOME to C:\Program Files\Java\jdk1.6.0_21 |
Linux | Export JAVA_HOME=/usr/local/java-current |
Mac | Export JAVA_HOME=/Library/Java/Home |
Javaコンパイラの場所をシステムパスに追加します。
OS | Output |
---|---|
Windows | Append the string ;%JAVA_HOME%\bin to the end of the system variable, Path. |
Linux | Export PATH=$PATH:$JAVA_HOME/bin/ |
Mac | Not required |
または、Borland JBuilder、Eclipse、IntelliJ IDEA、またはSun ONE Studioなどの統合開発環境(IDE)を使用する場合は、簡単なプログラムをコンパイルおよび実行して、IDEがJavaをインストールした場所を認識していることを確認します。 それ以外の場合は、IDEの所定のドキュメントに従って適切なセットアップを実行します。
ステップ3:Eclipse IDEをセットアップする
このチュートリアルのすべての例は、Eclipse IDEを使用して作成されています。 そのため、オペレーティングシステムに基づいて、Eclipseの最新バージョンをマシンにインストールすることをお勧めします。
Eclipse IDEをインストールするには、https://www.eclipse.org/downloads/からWTPサポート付きの最新のEclipseバイナリをダウンロードします。 インストールをダウンロードしたら、バイナリ配布物を便利な場所に解凍します。 たとえば、WindowsのC:\ eclipse、またはLinux/Unixの/usr/local/eclipseで、最後にPATH変数を適切に設定します。
Eclipseは、Windowsマシンで次のコマンドを実行することで開始できます。または、eclipse.exeをダブルクリックするだけで開始できます
%C:\eclipse\eclipse.exe
Eclipseは、Unix(Solaris、Linuxなど)マシンで次のコマンドを実行することで起動できます-
$/usr/local/eclipse/eclipse
正常に起動した後、すべてが正常であれば、次の結果が表示されます。
*注-次のeclipseソフトウェア更新サイトを使用して、m2eclipseプラグインをeclipseにインストールします
m2eclipseプラグイン-https://www.eclipse.org/m2e/[https://m2eclipse.sonatype.org/update/]。
このプラグインにより、開発者はEclipse内でmavenコマンドを組み込み/外部のMavenインストールで実行できます。
ステップ4:Mavenアーカイブをダウンロードする
[[1]] 2.2.1をダウンロードします
OS | Archive name |
---|---|
Windows | apache-maven-2.0.11-bin.zip |
Linux | apache-maven-2.0.11-bin.tar.gz |
Mac | apache-maven-2.0.11-bin.tar.gz |
ステップ5:Mavenアーカイブを抽出する
Maven 2.2.1をインストールするディレクトリにアーカイブを抽出します。 サブディレクトリapache-maven-2.2.1がアーカイブから作成されます。
OS | Location (can be different based on your installation) |
---|---|
Windows | C:\Program Files\Apache Software Foundation\apache-maven-2.2.1 |
Linux | /usr/local/apache-maven |
Mac | /usr/local/apache-maven |
ステップ6:Maven環境変数を設定する
M2_HOME、M2、MAVEN_OPTSを環境変数に追加します。
OS | Output |
---|---|
Windows |
Set the environment variables using system properties. M2_HOME = C:\ Program Files \ Apache Software Foundation \ apachemaven-2.2.1 M2 =%M2_HOME%\ bin MAVEN_OPTS = -Xms256m -Xmx512m |
Linux |
Open command terminal and set environment variables. export M2_HOME =/usr/local/apache-maven/apache-maven-2.2.1 export M2 =%M2_HOME%\ bin export MAVEN_OPTS = -Xms256m -Xmx512m |
Mac |
Open command terminal and set environment variables. export M2_HOME =/usr/local/apache-maven/apache-maven-2.2.1 export M2 =%M2_HOME%\ bin export MAVEN_OPTS = -Xms256m -Xmx512m |
ステップ7:Maven binディレクトリの場所をシステムパスに追加する
次に、システムパスにM2変数を追加します。
OS | Output |
---|---|
Windows | Append the string ;%M2% to the end of the system variable, Path. |
Linux | export PATH=$M2:$PATH |
Mac | export PATH=$M2:$PATH |
ステップ8:Mavenのインストールを確認します。
コンソールを開き、次のmvnコマンドを実行します。
OS | Task | Command |
---|---|---|
Windows | Open Command Console | c:\> mvn --version |
Linux | Open Command Terminal | $ mvn --version |
Mac | Open Terminal | machine:~ joseph$ mvn --version |
最後に、上記のコマンドの出力を確認します。これは次の表に示すとおりです。
OS | Output |
---|---|
Windows |
Apache Maven 2.2.1 (r801777; 2009-08-07 00:46:01+0530) Javaバージョン:1.6.0_21 Javaホーム:C:\ Program Files \ Java \ jdk1.6.0_21 \ jre |
Linux |
Apache Maven 2.2.1 (r801777; 2009-08-07 00:46:01+0530) Javaバージョン:1.6.0_21 Javaホーム:C:\ Program Files \ Java \ jdk1.6.0_21 \ jre |
Mac |
Apache Maven 2.2.1 (r801777; 2009-08-07 00:46:01+0530) Javaバージョン:1.6.0_21 Javaホーム:C:\ Program Files \ Java \ jdk1.6.0_21 \ jre |
ステップ9:Apache Tomcatのセットアップ
Tomcatの最新バージョンはhttps://tomcat.apache.org/からダウンロードできます。 インストールをダウンロードしたら、バイナリ配布物を便利な場所に解凍します。 たとえば、WindowsのC:\ apache-tomcat-6.0.33、またはLinux/Unixの/usr/local/apache-tomcat-6.0.33で、インストール場所を指すCATALINA_HOME環境変数を設定します。
Tomcatは、Windowsマシンで次のコマンドを実行することで起動できます。または、startup.batをダブルクリックするだけで起動できます。
%CATALINA_HOME%\bin\startup.bat
or
C:\apache-tomcat-6.0.33\bin\startup.bat
Tomcatは、Unix(Solaris、Linuxなど)マシンで次のコマンドを実行することで起動できます。
$CATALINA_HOME/bin/startup.sh
or
/usr/local/apache-tomcat-6.0.33/bin/startup.sh
正常に起動した後、Tomcatに含まれているデフォルトのWebアプリケーションは、 http://localhost:8080/ にアクセスして利用できます。 すべてが正常であれば、次の結果が表示されます。
Tomcatの設定と実行に関する詳細は、TomcatのWebサイト(http://tomcat.apache.org)だけでなく、ここに含まれているドキュメントにも記載されています。
Tomcatは、Windowsマシンで次のコマンドを実行することで停止できます。
%CATALINA_HOME%\bin\shutdown
or
C:\apache-tomcat-5.5.29\bin\shutdown
Tomcatは、Unix(Solaris、Linuxなど)マシンで次のコマンドを実行することで停止できます。
$CATALINA_HOME/bin/shutdown.sh
or
/usr/local/apache-tomcat-5.5.29/bin/shutdown.sh
JSF-アーキテクチャ
JSFテクノロジーは、サーバー側のユーザーインターフェイスコンポーネントを開発、構築し、それらをWebアプリケーションで使用するためのフレームワークです。 JSFテクノロジーは、ロジックをプレゼンテーションから分離するためのModel View Controller(MVC)アーキテクチャに基づいています。
MVCデザインパターンとは何ですか?
MVC設計パターンは、3つの別々のモジュールを使用してアプリケーションを設計します-
S.No | Module & Description |
---|---|
1 |
Model データの転送とログイン |
2 |
View ユーザーインターフェースを表示 |
3 |
Controller アプリケーションの処理を処理します。 |
MVCデザインパターンの目的は、モデルとプレゼンテーションを分離し、開発者がコアスキルに集中し、より明確にコラボレーションできるようにすることです。
Webデザイナーは、モデル層とコントローラー層ではなく、ビュー層のみに集中する必要があります。 開発者はモデルのコードを変更でき、通常はビューレイヤーを変更する必要はありません。 コントローラは、ユーザーアクションを処理するために使用されます。 このプロセスでは、レイヤーモデルとビューが変更される場合があります。
JSFアーキテクチャ
JSFアプリケーションは、他のJavaテクノロジーベースのWebアプリケーションに似ています。それはJavaサーブレットコンテナで実行され、含まれています-
- アプリケーション固有の機能とデータを含むモデルとしてのJavaBeansコンポーネント
- イベントハンドラーとバリデーターを表すカスタムタグライブラリ
- UIコンポーネントをレンダリングするためのカスタムタグライブラリ
- サーバー上のステートフルオブジェクトとして表されるUIコンポーネント
- サーバー側ヘルパークラス
- バリデーター、イベントハンドラー、およびナビゲーションハンドラー
- アプリケーションリソースを構成するためのアプリケーション構成リソースファイル
ユーザーアクションを実行するために使用できるコントローラーがあります。 UIはWebページ作成者が作成でき、ビジネスロジックはマネージドBeanで利用できます。
JSFは、個々のコンポーネントをレンダリングするためのいくつかのメカニズムを提供します。 目的の表現を選択するのはWebページのデザイナー次第であり、アプリケーション開発者は、JSF UIコンポーネントのレンダリングに使用されたメカニズムを知る必要はありません。
JSF-ライフサイクル
JSFアプリケーションのライフサイクルは、次の6つのフェーズで構成されます-
- ビューフェーズを復元する
- 要求値の適用フェーズ。プロセスイベント
- プロセス検証フェーズ。プロセスイベント
- モデル値の更新フェーズ。プロセスイベント
- アプリケーションフェーズを呼び出します。プロセスイベント
- 応答フェーズのレンダリング
6つのフェーズは、JSFがフォームを処理する順序を示しています。 リストには、各フェーズでのイベント処理を伴う可能性のある実行順序でフェーズが表示されます。
フェーズ1:ビューの復元
JSFは、リンクまたはボタンがクリックされ、JSFがリクエストを受信するとすぐに、ビューの復元フェーズを開始します。
この段階で、JSFはビューを構築し、イベントハンドラーとバリデーターをUIコンポーネントに接続し、FacesContextインスタンスにビューを保存します。 FacesContextインスタンスには、リクエストの処理に必要なすべての情報が含まれるようになりました。
フェーズ2:要求値を適用する
コンポーネントツリーが作成/復元された後、コンポーネントツリーの各コンポーネントはデコードメソッドを使用して、リクエストパラメータから新しい値を抽出します。 コンポーネントはこの値を保存します。 変換が失敗すると、エラーメッセージが生成され、FacesContextのキューに入れられます。 このメッセージは、検証エラーとともに、応答のレンダリング段階で表示されます。
現在のFacesContextインスタンスでrenderResponseと呼ばれるデコードメソッドイベントリスナーがある場合、JSFは応答のレンダリングフェーズに移動します。
フェーズ3:プロセス検証
このフェーズでは、JSFはコンポーネントツリーに登録されているすべてのバリデーターを処理します。 検証のためのコンポーネント属性ルールを調べ、これらのルールをコンポーネントに保存されているローカル値と比較します。
ローカル値が無効な場合、JSFはエラーメッセージをFacesContextインスタンスに追加し、ライフサイクルはレンダリングレスポンスフェーズに進み、エラーメッセージとともに同じページを再度表示します。
フェーズ4:モデル値の更新
JSFは、データが有効であることを確認した後、コンポーネントツリーを走査し、対応するサーバー側オブジェクトプロパティをコンポーネントのローカル値に設定します。 JSFは、入力コンポーネントの値属性に対応するBeanプロパティを更新します。
updateModelsメソッドが現在のFacesContextインスタンスでrenderResponseを呼び出した場合、JSFは応答のレンダリングフェーズに移動します。
フェーズ5:アプリケーションの呼び出し
この段階で、JSFは、フォームの送信や別のページへのリンクなど、アプリケーションレベルのイベントを処理します。
フェーズ6:応答のレンダリング
このフェーズでは、アプリケーションがJSPページを使用している場合、JSFはコンテナ/アプリケーションサーバーにページのレンダリングを要求します。 最初のリクエストでは、JSPコンテナがページを実行すると、ページに表示されるコンポーネントがコンポーネントツリーに追加されます。 これが最初の要求ではない場合、コンポーネントツリーは既に構築されているため、コンポーネントを再度追加する必要はありません。 どちらの場合でも、JSPコンテナ/アプリケーションサーバーがページ内のタグをトラバースすると、コンポーネントは自身をレンダリングします。
ビューのコンテンツがレンダリングされた後、応答状態は保存され、後続の要求がアクセスできるようになり、ビューの復元フェーズで使用できるようになります。
JSF-最初のアプリケーション
単純なJSFアプリケーションを作成するには、maven-archetype-webappプラグインを使用します。 次の例では、C:\ JSFフォルダーにMavenベースのWebアプリケーションプロジェクトを作成します。
プロジェクトを作成
コマンドコンソールを開き、 C:\> JSF ディレクトリに移動して、次の mvn コマンドを実行します。
C:\JSF>mvn archetype:create
-DgroupId = com.finddevguides.test
-DartifactId = helloworld
-DarchetypeArtifactId = maven-archetype-webapp
Mavenは処理を開始し、完全なJava Webアプリケーションプロジェクト構造を作成します。
[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'archetype'.
[INFO] -------------------------------------------------------------
[INFO] Building Maven Default Project
[INFO] task-segment: [archetype:create] (aggregator-style)
[INFO] -------------------------------------------------------------
[INFO] [archetype:create {execution: default-cli}]
[INFO] Defaulting package to group ID: com.finddevguides.test
[INFO] artifact org.apache.maven.archetypes:maven-archetype-webapp:
checking for updates from central
[INFO] -------------------------------------------------------------
[INFO] Using following parameters for creating project
from Old (1.x) Archetype: maven-archetype-webapp:RELEASE
[INFO] -------------------------------------------------------------
[INFO] Parameter: groupId, Value: com.finddevguides.test
[INFO] Parameter: packageName, Value: com.finddevguides.test
[INFO] Parameter: package, Value: com.finddevguides.test
[INFO] Parameter: artifactId, Value: helloworld
[INFO] Parameter: basedir, Value: C:\JSF
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] project created from Old (1.x) Archetype in dir:
C:\JSF\helloworld
[INFO] -------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] -------------------------------------------------------------
[INFO] Total time: 7 seconds
[INFO] Finished at: Mon Nov 05 16:05:04 IST 2012
[INFO] Final Memory: 12M/84M
[INFO] -------------------------------------------------------------
次に、C:/JSFディレクトリに移動します。 helloworld(artifactIdで指定されている)という名前のJava Webアプリケーションプロジェクトが作成されます。 Mavenは、次のスクリーンショットに示すように、標準のディレクトリレイアウトを使用します。
上記の例を使用すると、次の重要な概念を理解できます。
S.No | Folder Structure & Description |
---|---|
1 |
helloworld srcフォルダーとpom.xmlが含まれています |
2 |
src/main/wepapp WEB-INFフォルダーとindex.jspページが含まれています |
3 |
src/main/resources イメージ/プロパティファイルが含まれています(上記の例では、この構造を手動で作成する必要があります) |
プロジェクトにJSF機能を追加する
次のJSF依存関係を追加します。
<dependencies>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.1.7</version>
</dependency>
</dependencies>
完全なPOM.xml
<project xmlns = "http://maven.apache.org/POM/4.0.0"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.finddevguides.test</groupId>
<artifactId>helloworld</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>helloworld Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.1.7</version>
</dependency>
</dependencies>
<build>
<finalName>helloworld</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Eclipseプロジェクトを準備する
コマンドコンソールを開きましょう。 C:\> JSF> helloworld ディレクトリに移動し、次の mvn コマンドを実行します。
C:\JSF\helloworld>mvn eclipse:eclipse -Dwtpversion = 2.0
Mavenは処理を開始し、Eclipse対応プロジェクトを作成し、wtp機能を追加します。
Downloading: http://repo.maven.apache.org/org/apache/maven/plugins/
maven-compiler-plugin/2.3.1/maven-compiler-plugin-2.3.1.pom
5K downloaded (maven-compiler-plugin-2.3.1.pom)
Downloading: http://repo.maven.apache.org/org/apache/maven/plugins/
maven-compiler-plugin/2.3.1/maven-compiler-plugin-2.3.1.jar
29K downloaded (maven-compiler-plugin-2.3.1.jar)
[INFO] Searching repository for plugin with prefix: 'eclipse'.
[INFO] ------------------------------------------------------------
[INFO] Building helloworld Maven Webapp
[INFO] task-segment: [eclipse:eclipse]
[INFO] ------------------------------------------------------------
[INFO] Preparing eclipse:eclipse
[INFO] No goals needed for project - skipping
[INFO] [eclipse:eclipse {execution: default-cli}]
[INFO] Adding support for WTP version 2.0.
[INFO] Using Eclipse Workspace: null
[INFO] Adding default classpath container: org.eclipse.jdt.
launching.JRE_CONTAINER
Downloading: http://repo.maven.apache.org/
com/sun/faces/jsf-api/2.1.7/jsf-api-2.1.7.pom
12K downloaded (jsf-api-2.1.7.pom)
Downloading: http://repo.maven.apache.org/
com/sun/faces/jsf-impl/2.1.7/jsf-impl-2.1.7.pom
10K downloaded (jsf-impl-2.1.7.pom)
Downloading: http://repo.maven.apache.org/
com/sun/faces/jsf-api/2.1.7/jsf-api-2.1.7.jar
619K downloaded (jsf-api-2.1.7.jar)
Downloading: http://repo.maven.apache.org/
com/sun/faces/jsf-impl/2.1.7/jsf-impl-2.1.7.jar
1916K downloaded (jsf-impl-2.1.7.jar)
[INFO] Wrote settings to C:\JSF\helloworld\.settings\
org.eclipse.jdt.core.prefs
[INFO] Wrote Eclipse project for "helloworld" to C:\JSF\helloworld.
[INFO]
[INFO] -----------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] -----------------------------------------------------------
[INFO] Total time: 6 minutes 7 seconds
[INFO] Finished at: Mon Nov 05 16:16:25 IST 2012
[INFO] Final Memory: 10M/89M
[INFO] -----------------------------------------------------------
Eclipseでプロジェクトをインポートする
手順は次のとおりです-
- インポートウィザードを使用して、Eclipseでプロジェクトをインポートします。
- ファイル→インポート…に移動します →ワークスペースへの既存プロジェクト。
- helloworldへのルートディレクトリを選択します。
- *プロジェクトをワークスペースにコピーして*チェックします。
- [完了]ボタンをクリックします。
- Eclipseは、ワークスペース C:\→Projects→Data→WorkSpace にプロジェクトをインポートしてコピーします。
web.xmlでFacesサーブレットを構成する
*webapp→WEB-INF* フォルダーでweb.xmlを見つけ、以下に示すように更新します。
<?xml version = "1.0" encoding = "UTF-8"?>
<web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns = "http://java.sun.com/xml/ns/javaee"
xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id = "WebApp_ID" version="2.5">
<welcome-file-list>
<welcome-file>faces/home.xhtml</welcome-file>
</welcome-file-list>
<!--
FacesServlet is main servlet responsible to handle all request.
It acts as central controller.
This servlet initializes the JSF components before the JSP is displayed.
-->
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
</web-app>
マネージドBeanを作成する
*src→main→java as com→finddevguides→test* の下にパッケージ構造を作成します。 このパッケージにHelloWorld.javaクラスを作成します。 以下に示すように、 *HelloWorld.java* のコードを更新します。
package com.finddevguides.test;
import javax.faces.bean.ManagedBean;
@ManagedBean(name = "helloWorld", eager = true)
public class HelloWorld {
public HelloWorld() {
System.out.println("HelloWorld started!");
}
public String getMessage() {
return "Hello World!";
}
}
JSFページを作成する
*webapp* フォルダーの下にhome.xhtmlページを作成します。 以下に示すように、 *home.xhtml* のコードを更新します。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>JSF Tutorial!</title>
</head>
<body>
#{helloWorld.getMessage()}
</body>
</html>
プロジェクトを構築する
手順は次のとおりです。
- Eclipseでhelloworldプロジェクトを選択
- 実行ウィザードを使用
- [実行]→[Mavenパッケージ]を選択します*
- Mavenはプロジェクトの構築を開始し、 C:\→Projects→Data→WorkSpace→helloworld→target フォルダーの下にhelloworld.warを作成します。
[INFO] Scanning for projects...
[INFO] -----------------------------------------------------
[INFO] Building helloworld Maven Webapp
[INFO]
[INFO] Id: com.finddevguides.test:helloworld:war:1.0-SNAPSHOT
[INFO] task-segment: [package]
[INFO] -----------------------------------------------------
[INFO] [resources:resources]
[INFO] Using default encoding to copy filtered resources.
[INFO] [compiler:compile]
[INFO] Nothing to compile - all classes are up to date
[INFO] [resources:testResources]
[INFO] Using default encoding to copy filtered resources.
[INFO] [compiler:testCompile]
[INFO] No sources to compile
[INFO] [surefire:test]
[INFO] Surefire report directory:
C:\Projects\Data\WorkSpace\helloworld\target\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
There are no tests to run.
Results :
Tests run: 0, Failures: 0, Errors: 0, Skipped: 0
[INFO] [war:war]
[INFO] Packaging webapp
[INFO] Assembling webapp[helloworld] in
[C:\Projects\Data\WorkSpace\helloworld\target\helloworld]
[INFO] Processing war project
[INFO] Webapp assembled in[150 msecs]
[INFO] Building war:
C:\Projects\Data\WorkSpace\helloworld\target\helloworld.war
[INFO] ------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------
[INFO] Total time: 3 seconds
[INFO] Finished at: Mon Nov 05 16:34:46 IST 2012
[INFO] Final Memory: 2M/15M
[INFO] ------------------------------------------------
WARファイルを展開する
手順は次のとおりです。
- Tomcatサーバーを停止します。
- helloworld.warファイルを* tomcatインストールディレクトリ→webappsフォルダー*にコピーします。
- Tomcatサーバーを起動します。
- webappsディレクトリ内を見てください。helloworldフォルダーが作成されているはずです。
- これで、helloworld.warがTomcat Webサーバールートに正常にデプロイされました。
アプリケーションを実行
WebブラウザーでURLを入力します: http://localhost:8080/helloworld/home.jsf アプリケーションを起動します。
サーバー名(localhost)とポート(8080)は、Tomcatの構成によって異なる場合があります。
JSF-マネージドBean
管理対象Beanは、JSFに登録されている通常のJava Beanクラスです。 つまり、マネージドBeanは、JSFフレームワークによって管理されるJava Beanです。 マネージドBeanには、getterおよびsetterメソッド、ビジネスロジック、またはバッキングBean(BeanにはすべてのHTMLフォーム値が含まれます)が含まれます。
マネージドBeanはUIコンポーネントのモデルとして機能します。 管理対象Beanは、JSFページからアクセスできます。
*JSF 1.2* では、マネージドBeanはfacesconfig.xmlなどのJSF構成ファイルに登録する必要がありました。 *JSF 2.0* 以降、管理Beanは注釈を使用して簡単に登録できます。 このアプローチにより、Beanとその登録が1か所に保持されるため、管理が容易になります。
XML設定の使用
<managed-bean>
<managed-bean-name>helloWorld</managed-bean-name>
<managed-bean-class>com.finddevguides.test.HelloWorld</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
<managed-bean>
<managed-bean-name>message</managed-bean-name>
<managed-bean-class>com.finddevguides.test.Message</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
注釈を使用する
@ManagedBean(name = "helloWorld", eager = true)
@RequestScoped
public class HelloWorld {
@ManagedProperty(value = "#{message}")
private Message message;
...
}
@ManagedBeanアノテーション
*@ ManagedBean* は、name属性で指定された名前を持つ管理対象BeanとしてBeanをマークします。 name属性が指定されていない場合、マネージドBean名はデフォルトで完全修飾クラス名のクラス名部分になります。 この場合、helloWorldになります。
もう1つの重要な属性は*熱心*です。 eager = "true"の場合、マネージドBeanは最初に要求される前に作成されます。そうでない場合、要求されたときにのみBeanが作成される "lazy"初期化が使用されます。
スコープ注釈
スコープアノテーションは、マネージドBeanが配置されるスコープを設定します。 スコープが指定されていない場合、Beanはデフォルトでスコープをリクエストします。 次の表で、各スコープについて簡単に説明します。
S.No | Scope & Description |
---|---|
1 |
@RequestScoped Beanは、HTTP要求/応答が存続する限り存続します。 HTTPリクエストに基づいて作成され、HTTPリクエストに関連付けられたHTTPレスポンスが終了すると破棄されます。 |
2 |
@NoneScoped Beanは、単一のEL評価の間存続します。 EL評価時に作成され、EL評価の直後に破棄されます。 |
3 |
@ViewScoped Beanは、ユーザーがブラウザーのウィンドウ/タブで同じJSFビューと対話している限り存続します。 HTTPリクエストで作成され、ユーザーが別のビューにポストバックすると破棄されます。 |
4 |
@SessionScoped Beanは、HTTPセッションが存続する限り存続します。 セッションでこのBeanに関係する最初のHTTP要求で作成され、HTTPセッションが無効化されると破棄されます。 |
5 |
@ApplicationScoped Beanは、Webアプリケーションが存続する限り存続します。 アプリケーションでこのBeanに関係する最初のHTTP要求で作成され(Webアプリケーションが起動し、@ ManagedBeanでeager = true属性が設定されると)、Webアプリケーションがシャットダウンすると破棄されます。 |
6 |
@CustomScoped Beanは、このスコープ用に作成されたカスタムマップ内のBeanのエントリが存続する限り存続します。 |
@ManagedPropertyアノテーション
JSFは、単純な静的依存性注入(DI)フレームワークです。 @ ManagedProperty 注釈を使用して、マネージドBeanのプロパティを別のマネージドBeanに注入できます。
応用例
マネージドBeanの上記のアノテーションをテストするテストJSFアプリケーションを作成しましょう。
Step | Description |
---|---|
1 | Create a project with a name helloworld under a package com.finddevguides.test as explained in the JSF - Create Application chapter. |
2 | Modify HelloWorld.java as explained below. Keep the rest of the files unchanged. |
3 | Create Message.java under a package com.finddevguides.test as explained below. |
4 | Compile and run the application to make sure business logic is working as per the requirements. |
5 | Finally, build the application in the form of war file and deploy it in Apache Tomcat Webserver. |
6 | Launch your web application using appropriate URL as explained below in the last step. |
HelloWorld.java
package com.finddevguides.test;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
@ManagedBean(name = "helloWorld", eager = true)
@RequestScoped
public class HelloWorld {
@ManagedProperty(value = "#{message}")
private Message messageBean;
private String message;
public HelloWorld() {
System.out.println("HelloWorld started!");
}
public String getMessage() {
if(messageBean != null) {
message = messageBean.getMessage();
}
return message;
}
public void setMessageBean(Message message) {
this.messageBean = message;
}
}
Message.java
package com.finddevguides.test;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
@ManagedBean(name = "message", eager = true)
@RequestScoped
public class Message {
private String message = "Hello World!";
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
home.xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>JSF Tutorial!</title>
</head>
<body>
#{helloWorld.message}
</body>
</html>
すべての変更を完了したら、JSF-アプリケーションの作成の章で行ったようにアプリケーションをコンパイルして実行します。 すべてがアプリケーションで問題ない場合、次の結果が生成されます。
JSF-ページナビゲーション
ナビゲーションルールは、ボタンまたはリンクがクリックされたときに表示されるビューを記述する、JSFフレームワークによって提供されるルールです。
ナビゲーションルールは、faces-config.xmlという名前のJSF構成ファイルで定義できます。 マネージドBeanで定義できます。
ナビゲーションルールには、結果のビューを表示できる条件に基づいた条件を含めることができます。 JSF 2.0は、ナビゲーションルールを定義する必要のない暗黙的なナビゲーションも提供します。
暗黙的なナビゲーション
JSF 2.0は、暗黙的なナビゲーション*という名前の*自動ビューページリゾルバー*メカニズムを提供します。 この場合、ビュー名をアクション属性に入れるだけで、JSFはデプロイされたアプリケーションで正しい *view ページを自動的に検索します。
JSFページの自動ナビゲーション
JSF UIコンポーネントのアクション属性にビュー名を設定します。
<h:form>
<h3>Using JSF outcome</h3>
<h:commandButton action = "page2" value = "Page2"/>
</h:form>
ここで、 Page2 ボタンをクリックすると、JSFはビュー名 page2 をpage2.xhtml拡張子として解決し、現在のディレクトリで対応するビューファイル page2.xhtml を見つけます。
マネージドBeanの自動ナビゲーション
マネージドBeanでメソッドを定義して、ビュー名を返します。
@ManagedBean(name = "navigationController", eager = true)
@RequestScoped
public class NavigationController implements Serializable {
public String moveToPage1() {
return "page1";
}
}
マネージドBeanを使用して、JSF UIコンポーネントのアクション属性でビュー名を取得します。
<h:form>
<h3> Using Managed Bean</h3>
<h:commandButton action = "#{navigationController.moveToPage1}"
value = "Page1"/glt;
</h:form>
ここで、 Page1 ボタンをクリックすると、JSFはビュー名 page1 をpage1.xhtml拡張子として解決し、現在のディレクトリで対応するビューファイル page1.xhtml を見つけます。
条件付きナビゲーション
マネージドBeanを使用すると、ナビゲーションを非常に簡単に制御できます。 マネージドBeanの次のコードを見てください。
@ManagedBean(name = "navigationController", eager = true)
@RequestScoped
public class NavigationController implements Serializable {
//this managed property will read value from request parameter pageId
@ManagedProperty(value = "#{param.pageId}")
private String pageId;
//condional navigation based on pageId
//if pageId is 1 show page1.xhtml,
//if pageId is 2 show page2.xhtml
//else show home.xhtml
public String showPage() {
if(pageId == null) {
return "home";
}
if(pageId.equals("1")) {
return "page1";
}else if(pageId.equals("2")) {
return "page2";
}else {
return "home";
}
}
}
JSF UIコンポーネントのリクエストパラメータとしてpageIdを渡します。
<h:form>
<h:commandLink action = "#{navigationController.showPage}" value = "Page1">
<f:param name = "pageId" value = "1"/>
</h:commandLink>
<h:commandLink action = "#{navigationController.showPage}" value = "Page2">
<f:param name = "pageId" value = "2"/>
</h:commandLink>
<h:commandLink action = "#{navigationController.showPage}" value = "Home">
<f:param name = "pageId" value = "3"/>
</h:commandLink>
</h:form>
ここで、「Page1」ボタンをクリックすると。
- JSFは、パラメーターpageId = 1でリクエストを作成します
- 次に、JSFはこのパラメーターをnavigationControllerの管理プロパティpageIdに渡します
- これで、navigationController.showPage()が呼び出され、pageIdを確認した後にviewをpage1として返します
- JSFはビュー名page1をpage1.xhtml拡張子として解決します
- 現在のディレクトリで対応するビューファイルpage1.xhtmlを見つけます
from-actionに基づくナビゲーションの解決
マネージドBeanの異なるメソッドが同じビュー名を返す場合でも、JSFはナビゲーション解決オプションを提供します。
マネージドBeanの次のコードを見てください。
public String processPage1() {
return "page";
}
public String processPage2() {
return "page";
}
ビューを解決するには、 faces-config.xml で次のナビゲーションルールを定義します
<navigation-rule>
<from-view-id>home.xhtml</from-view-id>
<navigation-case>
<from-action>#{navigationController.processPage1}</from-action>
<from-outcome>page</from-outcome>
<to-view-id>page1.jsf</to-view-id>
</navigation-case>
<navigation-case>
<from-action>#{navigationController.processPage2}</from-action>
<from-outcome>page</from-outcome>
<to-view-id>page2.jsf</to-view-id>
</navigation-case>
</navigation-rule>
ここで、Page1ボタンがクリックされたとき-
- * navigationController.processPage1()*が呼び出され、ページとしてビューが返されます
- ビュー名は* page1で、 faces-configのfrom-action はnavigationController.processPage1 であるため、JSFはビュー名 *page1 を解決します。
- 現在のディレクトリで対応するビューファイル page1.xhtml を見つけます。
フォワードとリダイレクト
デフォルトでは、JSFは別のページにナビゲートしている間にサーバーページを転送し、アプリケーションのURLは変更されません。
ページのリダイレクトを有効にするには、ビュー名の最後に faces-redirect = true を追加します。
<h:form>
<h3>Forward</h3>
<h:commandButton action = "page1" value = "Page1"/>
<h3>Redirect</h3>
<h:commandButton action = "page1?faces-redirect = true" value = "Page1"/>
</h:form>
ここで、 Forward の下の Page1 ボタンをクリックすると、次の結果が得られます。
ここで、リダイレクト*の下の *Page1 ボタンをクリックすると、次の結果が得られます。
応用例
上記のすべてのナビゲーションの例をテストするために、テストJSFアプリケーションを作成しましょう。
Step | Description |
---|---|
1 | Create a project with a name helloworld under a package com.finddevguides.test as explained in the JSF - Create Application chapter. |
2 | Create NavigationController.java under a package com.finddevguides.test as explained below. |
3 | Create faces-config.xml under a WEB-INF folder and updated its contents as explained below. |
4 | Update web.xml under a WEB-INF folder as explained below. |
5 | Create page1.xhtml and page2.xhtml and modify home.xhtml under a webapp folder as explained below. |
6 | Compile and run the application to make sure business logic is working as per the requirements. |
7 | Finally, build the application in the form of war file and deploy it in Apache Tomcat Webserver. |
8 | Launch your web application using appropriate URL as explained below in the last step. |
package com.finddevguides.test;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
@ManagedBean(name = "navigationController", eager = true)
@RequestScoped
public class NavigationController implements Serializable {
private static final long serialVersionUID = 1L;
@ManagedProperty(value = "#{param.pageId}")
private String pageId;
public String moveToPage1() {
return "page1";
}
public String moveToPage2() {
return "page2";
}
public String moveToHomePage() {
return "home";
}
public String processPage1() {
return "page";
}
public String processPage2() {
return "page";
}
public String showPage() {
if(pageId == null) {
return "home";
}
if(pageId.equals("1")) {
return "page1";
}else if(pageId.equals("2")) {
return "page2";
}else {
return "home";
}
}
public String getPageId() {
return pageId;
}
public void setPageId(String pageId) {
this.pageId = pageId;
}
}
faces-config.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<faces-config
xmlns = "http://java.sun.com/xml/ns/javaee"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version = "2.0">
<navigation-rule>
<from-view-id>home.xhtml</from-view-id>
<navigation-case>
<from-action>#{navigationController.processPage1}</from-action>
<from-outcome>page</from-outcome>
<to-view-id>page1.jsf</to-view-id>
</navigation-case>
<navigation-case>
<from-action>#{navigationController.processPage2}</from-action>
<from-outcome>page</from-outcome>
<to-view-id>page2.jsf</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<context-param>
<param-name>javax.faces.CONFIG_FILES</param-name>
<param-value>/WEB-INF/faces-config.xml</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
</web-app>
page1.xhtml
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:h = "http://java.sun.com/jsf/html">
<h:body>
<h2>This is Page1</h2>
<h:form>
<h:commandButton action = "home?faces-redirect = true"
value = "Back To Home Page"/>
</h:form>
</h:body>
</html>
page2.xhtml
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:h = "http://java.sun.com/jsf/html">
<h:body>
<h2>This is Page2</h2>
<h:form>
<h:commandButton action = "home?faces-redirect = true"
value = "Back To Home Page"/>
</h:form>
</h:body>
</html>
home.xhtml
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:f = "http://java.sun.com/jsf/core"
xmlns:h = "http://java.sun.com/jsf/html">
<h:body>
<h2>Implicit Navigation</h2>
<hr/>
<h:form>
<h3>Using Managed Bean</h3>
<h:commandButton action = "#{navigationController.moveToPage1}"
value = "Page1"/>
<h3>Using JSF outcome</h3>
<h:commandButton action = "page2" value = "Page2"/>
</h:form>
<br/>
<h2>Conditional Navigation</h2>
<hr/>
<h:form>
<h:commandLink action = "#{navigationController.showPage}"
value="Page1">
<f:param name = "pageId" value = "1"/>
</h:commandLink>
<h:commandLink action = "#{navigationController.showPage}"
value="Page2">
<f:param name = "pageId" value = "2"/>
</h:commandLink>
<h:commandLink action = "#{navigationController.showPage}"
value = "Home">
<f:param name = "pageId" value = "3"/>
</h:commandLink>
</h:form>
<br/>
<h2>"From Action" Navigation</h2>
<hr/>
<h:form>
<h:commandLink action = "#{navigationController.processPage1}"
value = "Page1"/>
<h:commandLink action = "#{navigationController.processPage2}"
value = "Page2"/>
</h:form>
<br/>
<h2>Forward vs Redirection Navigation</h2>
<hr/>
<h:form>
<h3>Forward</h3>
<h:commandButton action = "page1" value = "Page1"/>
<h3>Redirect</h3>
<h:commandButton action = "page1?faces-redirect = true"
value = "Page1"/>
</h:form>
</h:body>
</html>
すべての変更を完了したら、JSF-アプリケーションの作成の章で行ったようにアプリケーションをコンパイルして実行します。 すべてがアプリケーションで問題ない場合、次の結果が生成されます。
JSF-基本タグ
この章では、さまざまなタイプの基本的なJSFタグについて学習します。
JSFは、標準のHTMLタグライブラリを提供します。 これらのタグは、対応するhtml出力にレンダリングされます。
これらのタグには、htmlノードで次のURIの名前空間を使用する必要があります。
<html
xmlns = "http://www.w3.org/1999/xhtml"
xmlns:h = "http://java.sun.com/jsf/html">
以下は、JSF 2.0の重要な基本タグです。
S.No | Tag & Description |
---|---|
1 |
type = "text"、テキストボックスのHTML入力をレンダリングします。 |
2 |
type = "password"、テキストボックスのHTML入力をレンダリングします。 |
3 |
HTML textareaフィールドをレンダリングします。 |
4 |
type = "hidden"のHTML入力をレンダリングします。 |
5 |
単一のHTMLチェックボックスを表示します。 |
6 |
HTMLチェックボックスのグループをレンダリングします。 |
7 |
単一のHTMLラジオボタンをレンダリングします。 |
8 |
HTMLシングルリストボックスをレンダリングします。 |
9 |
HTMLの複数のリストボックスをレンダリングします。 |
10 |
HTMLコンボボックスをレンダリングします。 |
11 |
HTMLテキストをレンダリングします。 |
12 |
HTMLテキストをレンダリングします。 パラメーターを受け入れます。 |
13 |
画像をレンダリングします。 |
14 |
HTML出力にCSSスタイルシートを含めます。 |
15 |
HTML出力にスクリプトを含めます。 |
16 |
type = "submit"ボタンのHTML入力をレンダリングします。 |
17 |
HTMLアンカーをレンダリングします。 |
18 |
HTMLアンカーをレンダリングします。 |
19 |
HTMLアンカーをレンダリングします。 |
20 |
グリッドの形式でHTMLテーブルをレンダリングします。 |
21 |
JSF UIコンポーネントのメッセージを表示します。 |
22 |
JSF UIコンポーネントのすべてのメッセージを表示します。 |
23 |
パラメーターをJSF UIコンポーネントに渡します。 |
24 |
JSF UIコンポーネントに属性を渡します。 |
25 |
マネージドBeanのプロパティの値を設定します。 |
JSF-Faceletsタグ
JSFは、faceletsタグと呼ばれるWebアプリケーションの共通レイアウトを作成するための特別なタグを提供します。 これらのタグは、複数のページの共通部分を1か所で管理する柔軟性を提供します。
これらのタグには、htmlノードで次のURIの名前空間を使用する必要があります。
<html
xmlns = "http://www.w3.org/1999/xhtml"
xmlns:ui = "http://java.sun.com/jsf/facelets">
以下は、JSF 2.0の重要なFaceletsタグです。
S.No | Tag & Description |
---|---|
1 |
次のタグを使用してテンプレートを使用する方法を示します
|
2 |
次のタグを使用して、テンプレートファイルにパラメーターを渡す方法を示します。
|
3 |
カスタムタグの作成方法を示します |
4 |
生成されたHTMLページからJSFコードを削除する機能を紹介します |
JSF-コンバータータグ
JSFは、UIコンポーネントのデータをマネージドBeanで使用されるオブジェクトに、またはその逆に変換する組み込みコンバーターを提供します。 たとえば、これらのタグはテキストを日付オブジェクトに変換し、入力の形式も検証できます。
これらのタグには、htmlノードで次のURIの名前空間を使用する必要があります。
<html
xmlns = "http://www.w3.org/1999/xhtml"
xmlns:f = "http://java.sun.com/jsf/core">
以下は、JSF 2.0の重要な_Convertorタグ_です-
S.No | Tag & Description |
---|---|
1 |
文字列を必要な形式の数に変換します |
2 |
文字列を目的の形式の日付に変換します |
3 |
カスタムコンバーターの作成 |
JSF-検証タグ
JSFは、UIコンポーネントを検証するための組み込みのバリデーターを提供します。 これらのタグは、フィールドの長さ、カスタムオブジェクトにできる入力のタイプを検証できます。
これらのタグには、htmlノードで次のURIの名前空間を使用する必要があります。
<html
xmlns = "http://www.w3.org/1999/xhtml"
xmlns:f = "http://java.sun.com/jsf/core">
以下は、JSF 2.0の重要な検証タグです。
S.No | Tag & Description |
---|---|
1 |
文字列の長さを検証します |
2 |
数値の範囲を検証します |
3 |
float値の範囲を検証します |
4 |
指定された正規表現でJSFコンポーネントを検証します |
5 |
カスタムバリデーターを作成します |
JSF-DataTable
JSFは、htmlテーブルをレンダリングおよびフォーマットするDataTableというリッチコントロールを提供します。
- DataTableは、値のコレクションまたは配列を反復処理してデータを表示できます。
- DataTableは、簡単にデータを変更するための属性を提供します。
HTMLヘッダー
<html
xmlns = "http://www.w3.org/1999/xhtml"
xmlns:h = "http://java.sun.com/jsf/html">
</html>
以下は、JSF 2.0での重要なDataTable操作です-
S.No | Tag & Description |
---|---|
1 |
dataTableを表示する方法 |
2 |
dataTableに新しい行を追加する方法 |
3 |
dataTableの行を編集する方法 |
4 |
dataTableの行を削除する方法 |
5 |
DataModelを使用して、dataTableの行番号を表示します |
JSF-複合コンポーネント
JSFは、独自のカスタムコンポーネントを定義する強力な機能を開発者に提供します。これを使用して、カスタムコンテンツをレンダリングできます。
カスタムコンポーネントの定義
JSFでのカスタムコンポーネントの定義は2段階のプロセスです。
Step | Description |
---|---|
1a |
Create a resources folder. 複合名前空間を使用して、resourcesフォルダーにxhtmlファイルを作成します。 |
1b | Use composite tags composite:interface, composite:attribute and composite:implementation, to define content of the composite component. Use cc.attrs in composite:implementation to get variable defined using composite:attribute in composite:interface. |
ステップ1a:カスタムコンポーネントの作成:loginComponent.xhtml
リソースフォルダーにfinddevguidesフォルダーを作成し、その中にファイルloginComponent.xhtmlを作成します。
HTMLヘッダーで複合名前空間を使用します。
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:h = "http://java.sun.com/jsf/html"
xmlns:f = "http://java.sun.com/jsf/core"
xmlns:composite = "http://java.sun.com/jsf/composite">
...
</html>
ステップ1b:複合タグの使用:loginComponent.xhtml
次の表では、複合タグの使用について説明します。
S.No | Tag & Description |
---|---|
1 |
composite:interface composite:implementationで使用される構成可能な値を宣言します。 |
2 |
composite:attribute 構成値は、このタグを使用して宣言されます。 |
3 |
composite:implementation JSFコンポーネントを宣言します。 #\ {cc.attrs.attribute-name}式を使用して、composite:interfaceで定義された構成可能な値にアクセスできます。 |
<composite:interface>
<composite:attribute name = "usernameLabel"/>
<composite:attribute name = "usernameValue"/>
</composite:interface>
<composite:implementation>
<h:form>
#{cc.attrs.usernameLabel} :
<h:inputText id = "username" value = "#{cc.attrs.usernameValue}"/>
</h:form>
カスタムコンポーネントを使用
JSFでカスタムコンポーネントを使用するのは簡単なプロセスです。
Step | Description |
---|---|
2a | Create a xhtml file and use custom component’s namespace. Namespace will the [<folder-name>|http://java.sun.com/jsf/<folder-name> ]; where folder-name is folder in resources directory containing the custom component |
2b | Use the custom component as normal JSF tags |
ステップ2a:カスタム名前空間を使用:home.xhtml
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:h = "http://java.sun.com/jsf/html"
xmlns:ui = "http://java.sun.com/jsf/facelets">
xmlns:tp = "http://java.sun.com/jsf/composite/finddevguides">
ステップ2b:カスタムタグの使用:home.xhtmlおよび値を渡す
<h:form>
<tp:loginComponent
usernameLabel = "Enter User Name: "
usernameValue = "#{userData.name}"/>
</h:form>
応用例
テストJSFアプリケーションを作成して、JSFのカスタムコンポーネントをテストしましょう。
Step | Description |
---|---|
1 | Create a project with a name helloworld under a package com.finddevguides.test as explained in the JSF - First Application chapter. |
2 | Create resources folder under src → main folder. |
3 | Create finddevguides folder under src → main → resources folder. |
4 | Create loginComponent.xhtml file under src → main → resources → finddevguides folder. |
5 | Modify UserData.java file as explained below. |
6 | Modify home.xhtml as explained below. Keep the rest of the files unchanged. |
7 | Compile and run the application to make sure the business logic is working as per the requirements. |
8 | Finally, build the application in the form of war file and deploy it in Apache Tomcat Webserver. |
9 | Launch your web application using appropriate URL as explained below in the last step. |
loginComponent.xhtml
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:h = "http://java.sun.com/jsf/html"
xmlns:f = "http://java.sun.com/jsf/core"
xmlns:composite = "http://java.sun.com/jsf/composite">
<composite:interface>
<composite:attribute name = "usernameLabel"/>
<composite:attribute name = "usernameValue"/>
<composite:attribute name = "passwordLabel"/>
<composite:attribute name = "passwordValue"/>
<composite:attribute name = "loginButtonLabel"/>
<composite:attribute name = "loginButtonAction"
method-signature = "java.lang.String login()"/>
</composite:interface>
<composite:implementation>
<h:form>
<h:message for = "loginPanel" style = "color:red;"/>
<h:panelGrid columns = "2" id = "loginPanel">
#{cc.attrs.usernameLabel} :
<h:inputText id = "username" value = "#{cc.attrs.usernameValue}"/>
#{cc.attrs.passwordLabel} :
<h:inputSecret id = "password" value = "#{cc.attrs.passwordValue}"/>
</h:panelGrid>
<h:commandButton action = "#{cc.attrs.loginButtonAction}"
value = "#{cc.attrs.loginButtonLabel}"/>
</h:form>
</composite:implementation>
</html>
UserData.java
package com.finddevguides.test;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean(name = "userData", eager = true)
@SessionScoped
public class UserData implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String login() {
return "result";
}
}
home.xhtml
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:h = "http://java.sun.com/jsf/html"
xmlns:f = "http://java.sun.com/jsf/core"
xmlns:tp = "http://java.sun.com/jsf/composite/finddevguides">
<h:head>
<title>JSF tutorial</title>
</h:head>
<h:body>
<h2>Custom Component Example</h2>
<h:form>
<tp:loginComponent
usernameLabel = "Enter User Name: "
usernameValue = "#{userData.name}"
passwordLabel = "Enter Password: "
passwordValue = "#{userData.password}"
loginButtonLabel = "Login"
loginButtonAction = "#{userData.login}"/>
</h:form>
</h:body>
</html>
すべての変更を完了したら、JSF-最初のアプリケーションの章で行ったようにアプリケーションをコンパイルして実行します。 すべてがアプリケーションで問題ない場合、次の結果が生成されます。
JSF-Ajax
AJAXは、Asynchronous JavaScript and Xmlの略です。
Ajaxは、JavaScriptのHTTPXMLObjectを使用して、サーバーにデータを送信し、サーバーから非同期にデータを受信する手法です。 したがって、Ajax技術を使用して、javascriptコードはサーバーとデータを交換し、ページ全体をリロードせずにWebページの一部を更新します。
JSFは、ajax呼び出しを行うための優れたサポートを提供します。 ajax呼び出しを処理するf:ajaxタグを提供します。
JSFタグ
<f:ajax execute = "input-component-name" render = "output-component-name"/>
タグ属性
S.No | Attribute & Description |
---|---|
1 |
disabled trueの場合、Ajaxの動作はすべての親コンポーネントまたは子コンポーネントに適用されます。 falseの場合、Ajaxの動作は無効になります。 |
2 |
Event 「クリック」、「変更」、「ぼかし」、「キープレス」など、Ajaxリクエストを呼び出すイベント。 |
3 |
Execute Ajaxリクエストに含める必要があるコンポーネントのIDのスペース区切りリスト。 |
4 |
Immediate この動作から生成された「true」動作イベントが、要求値の適用フェーズ中にブロードキャストされる場合。 それ以外の場合、イベントはアプリケーションの呼び出し段階でブロードキャストされます。 |
5 |
Listener Ajaxリクエスト中に呼び出されるバッキングBeanのメソッドのEL式。 |
6 |
Onerror Ajaxリクエスト中にエラーが発生した場合に呼び出されるJavaScriptコールバック関数の名前。 |
7 |
Onevent UIイベントを処理するために呼び出されるJavaScriptコールバック関数の名前。 |
8 |
Render Ajaxリクエスト後に更新されるコンポーネントのIDのスペース区切りリスト。 |
応用例
テストJSFアプリケーションを作成して、JSFのカスタムコンポーネントをテストしましょう。
Step | Description |
---|---|
1 | Create a project with a name helloworld under a package com.finddevguides.test as explained in the JSF - First Application chapter. |
2 | Modify UserData.java file as explained below. |
3 | Modify home.xhtml as explained below. Keep the rest of the files unchanged. |
4 | Compile and run the application to make sure the business logic is working as per the requirements. |
5 | Finally, build the application in the form of war file and deploy it in Apache Tomcat Webserver. |
6 | Launch your web application using appropriate URL as explained below in the last step. |
UserData.java
package com.finddevguides.test;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean(name = "userData", eager = true)
@SessionScoped
public class UserData implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getWelcomeMessage() {
return "Hello " + name;
}
}
home.xhtml
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:h = "http://java.sun.com/jsf/html"
xmlns:f = "http://java.sun.com/jsf/core"
xmlns:tp = "http://java.sun.com/jsf/composite/finddevguides">
<h:head>
<title>JSF tutorial</title>
</h:head>
<h:body>
<h2>Ajax Example</h2>
<h:form>
<h:inputText id = "inputName" value = "#{userData.name}"></h:inputText>
<h:commandButton value = "Show Message">
<f:ajax execute = "inputName" render = "outputMessage"/>
</h:commandButton>
<h2><h:outputText id = "outputMessage"
value = "#{userData.welcomeMessage != null ?
userData.welcomeMessage : ''}"
/></h2>
</h:form>
</h:body>
</html>
すべての変更を完了したら、JSF-最初のアプリケーションの章で行ったようにアプリケーションをコンパイルして実行します。 すべてがアプリケーションで問題ない場合、次の結果が生成されます。
名前を入力し、メッセージの表示ボタンを押します。 ページの更新/フォーム送信なしで次の結果が表示されます。
JSF-イベント処理
ユーザーがJSFボタンまたはリンクをクリックするか、テキストフィールドの値を変更すると、JSF UIコンポーネントはイベントを発生させます。これはアプリケーションコードによって処理されます。 このようなイベントを処理するには、イベントハンドラーをアプリケーションコードまたはマネージドBeanに登録します。
UIコンポーネントは、ユーザーイベントが発生したことを確認すると、対応するイベントクラスのインスタンスを作成し、イベントリストに追加します。 次に、コンポーネントはイベントを起動します。つまり、そのイベントのリスナーのリストをチェックし、各リスナーまたはハンドラーでイベント通知メソッドを呼び出します。
JSFは、システムレベルのイベントハンドラも提供します。これは、アプリケーションの起動時または停止時にいくつかのタスクを実行するために使用できます。
以下は、JSF 2.0のいくつかの重要な_Event Handler_です-
S.No | Event Handlers & Description |
---|---|
1 |
ユーザーが入力コンポーネントを変更すると、値変更イベントが発生します。 |
2 |
ユーザーがボタンまたはリンクコンポーネントをクリックすると、アクションイベントが発生します。 |
3 |
JSFライフサイクル中に発生するイベント:PostConstructApplicationEvent、PreDestroyApplicationEvent、PreRenderViewEvent。 |
JSF-JDBC統合
この記事では、JDBCを使用してJSFにデータベースを統合する方法を示します。
この例を実行するためのデータベース要件は次のとおりです。
S.No | Software & Description |
---|---|
1 |
オープンソースおよび軽量データベース |
2 |
PostgreSQL 9.1およびJDK 1.5以上のJDBCドライバー |
PostgreSQL JDBC4ドライバーjarをTomcat Webサーバーのlibディレクトリに配置します。
データベースSQLコマンド
create user user1;
create database testdb with owner = user1;
CREATE TABLE IF NOT EXISTS authors (
id int PRIMARY KEY,
name VARCHAR(25)
);
INSERT INTO authors(id, name) VALUES(1, 'Rob Bal');
INSERT INTO authors(id, name) VALUES(2, 'John Carter');
INSERT INTO authors(id, name) VALUES(3, 'Chris London');
INSERT INTO authors(id, name) VALUES(4, 'Truman De Bal');
INSERT INTO authors(id, name) VALUES(5, 'Emile Capote');
INSERT INTO authors(id, name) VALUES(7, 'Breech Jabber');
INSERT INTO authors(id, name) VALUES(8, 'Bob Carter');
INSERT INTO authors(id, name) VALUES(9, 'Nelson Mand');
INSERT INTO authors(id, name) VALUES(10, 'Tennant Mark');
alter user user1 with password 'user1';
grant all on authors to user1;
応用例
JDBC統合をテストするテストJSFアプリケーションを作成しましょう。
Step | Description |
---|---|
1 | Create a project with a name helloworld under a package com.finddevguides.test as explained in the JSF - First Application chapter. |
2 | Create resources folder under src → main folder. |
3 | Create css folder under src → main → resources folder. |
4 | Create styles.css file under src → main → resources → css folder. |
5 | Modify styles.css file as explained below. |
6 | Modify pom.xml as explained below. |
7 | Create Author.java under package com.finddevguides.test as explained below. |
8 | Create UserData.java under package com.finddevguides.test as explained below. |
9 | Modify home.xhtml as explained below. Keep the rest of the files unchanged. |
10 | Compile and run the application to make sure the business logic is working as per the requirements. |
11 | Finally, build the application in the form of war file and deploy it in Apache Tomcat Webserver. |
12 | Launch your web application using appropriate URL as explained below in the last step. |
styles.css
.authorTable {
border-collapse:collapse;
border-bottom:1px solid #000000;
}
.authorTableHeader {
text-align:center;
background:none repeat scroll 0 0 #B5B5B5;
border-bottom:1px solid #000000;
border-top:1px solid #000000;
padding:2px;
}
.authorTableOddRow {
text-align:center;
background:none repeat scroll 0 0 #FFFFFFF;
}
.authorTableEvenRow {
text-align:center;
background:none repeat scroll 0 0 #D3D3D3;
}
pom.xml
<project xmlns = "http://maven.apache.org/POM/4.0.0"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.finddevguides.test</groupId>
<artifactId>helloworld</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>helloworld Maven Webapp</name>
<url>http://maven.apache.org</url >
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901.jdbc4</version>
</dependency>
</dependencies>
<build>
<finalName>helloworld</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<id>copy-resources</id>
<phase>validate</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${basedir}/target/helloworld/resources
</outputDirectory>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Author.java
package com.finddevguides.test;
public class Author {
int id;
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
UserData.java
package com.finddevguides.test;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ComponentSystemEvent;
@ManagedBean(name = "userData", eager = true)
@SessionScoped
public class UserData implements Serializable {
private static final long serialVersionUID = 1L;
public List<Author> getAuthors() {
ResultSet rs = null;
PreparedStatement pst = null;
Connection con = getConnection();
String stm = "Select * from authors";
List<Author> records = new ArrayList<Author>();
try {
pst = con.prepareStatement(stm);
pst.execute();
rs = pst.getResultSet();
while(rs.next()) {
Author author = new Author();
author.setId(rs.getInt(1));
author.setName(rs.getString(2));
records.add(author);
}
} catch (SQLException e) {
e.printStackTrace();
}
return records;
}
public Connection getConnection() {
Connection con = null;
String url = "jdbc:postgresql://localhost/testdb";
String user = "user1";
String password = "user1";
try {
con = DriverManager.getConnection(url, user, password);
System.out.println("Connection completed.");
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
finally {
}
return con;
}
}
home.xhtml
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:f = "http://java.sun.com/jsf/core"
xmlns:h = "http://java.sun.com/jsf/html">
<h:head>
<title>JSF Tutorial!</title>
<h:outputStylesheet library = "css" name = "styles.css" />
</h:head>
<h:body>
<h2>JDBC Integration Example</h2>
<h:dataTable value = "#{userData.authors}" var = "c"
styleClass = "authorTable"
headerClass = "authorTableHeader"
rowClasses = "authorTableOddRow,authorTableEvenRow">
<h:column><f:facet name = "header">Author ID</f:facet>
#{c.id}
</h:column>
<h:column><f:facet name = "header">Name</f:facet>
#{c.name}
</h:column>
</h:dataTable>
</h:body>
</html>
すべての変更を完了したら、JSF-最初のアプリケーションの章で行ったようにアプリケーションをコンパイルして実行します。 すべてがアプリケーションで問題ない場合、次の結果が生成されます。
JSF-Springの統合
Springは、JSFとSpringをシームレスに統合する特別なクラスDelegatingVariableResolverを提供します。
JSFにSpring Dependency Injection(IOC)機能を統合するには、次の手順が必要です。
ステップ1:DelegatingVariableResolverを追加する
faces-config.xmlにvariable-resolverエントリを追加して、Springクラス DelegatingVariableResolver をポイントします。
<faces-config>
<application>
<variable-resolver>
org.springframework.web.jsf.DelegatingVariableResolver
</variable-resolver>
...
</faces-config>
ステップ2:コンテキストリスナーを追加する
web.xmlのspringフレームワークによって提供される ContextLoaderListener および RequestContextListener リスナーを追加します。
<web-app>
...
<!-- Add Support for Spring -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
...
</web-app>
ステップ3:依存関係を定義する
管理対象Beanの依存関係として使用されるapplicationContext.xmlでBeanを定義します。
<beans>
<bean id = "messageService"
class = "com.finddevguides.test.MessageServiceImpl">
<property name = "message" value = "Hello World!"/>
</bean>
</beans>
ステップ4:依存関係を追加する
*DelegatingVariableResolver* は、最初に値ルックアップをJSFのデフォルトリゾルバーに委任し、次にSpringのWebApplicationContextに委任します。 これにより、スプリングベースの依存関係をJSF管理のBeanに簡単に挿入できます。
ここでは、スプリングベースの依存関係としてmessageServiceを注入しました。
<faces-config>
...
<managed-bean>
<managed-bean-name>userData</managed-bean-name>
<managed-bean-class>com.finddevguides.test.UserData</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>messageService</property-name>
<value>#{messageService}</value>
</managed-property>
</managed-bean>
</faces-config>
ステップ5:依存関係を使用する
//jsf managed bean
public class UserData {
//spring managed dependency
private MessageService messageService;
public void setMessageService(MessageService messageService) {
this.messageService = messageService;
}
public String getGreetingMessage() {
return messageService.getGreetingMessage();
}
}
応用例
テストJSFアプリケーションを作成して、スプリング統合をテストしましょう。
Step | Description |
---|---|
1 | Create a project with a name helloworld under a package com.finddevguides.test as explained in the JSF - First Application chapter. |
2 | Modify pom.xml as explained below. |
3 | Create faces-config.xml in WEB-INF folder as explained below. |
4 | Modify web.xml as explained below. |
5 | Create applicationContext.xml in WEB-INF folder as explained below. |
6 | Create MessageService.java under package com.finddevguides.test as explained below. |
7 | Create MessageServiceImpl.java under package com.finddevguides.test as explained below. |
8 | Create UserData.java under package com.finddevguides.test as explained below. |
9 | Modify home.xhtml as explained below. Keep the rest of the files unchanged. |
10 | Compile and run the application to make sure the business logic is working as per the requirements. |
11 | Finally, build the application in the form of war file and deploy it in Apache Tomcat Webserver. |
12 | Launch your web application using appropriate URL as explained below in the last step. |
pom.xml
<project xmlns = "http://maven.apache.org/POM/4.0.0"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.finddevguides.test</groupId>
<artifactId>helloworld</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>helloworld Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
</dependencies>
<build>
<finalName>helloworld</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<id>copy-resources</id>
<phase>validate</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${basedir}/target/helloworld/resources
</outputDirectory>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
faces-config.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<faces-config
xmlns = "http://java.sun.com/xml/ns/javaee"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version = "2.0">
<application>
<variable-resolver>
org.springframework.web.jsf.DelegatingVariableResolver
</variable-resolver>
</application>
<managed-bean>
<managed-bean-name>userData</managed-bean-name>
<managed-bean-class>com.finddevguides.test.UserData</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>messageService</property-name>
<value>#{messageService}</value>
</managed-property>
</managed-bean>
</faces-config>
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<!-- Add Support for Spring -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
</web-app>
applicationContext.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id = "messageService"
class = "com.finddevguides.test.MessageServiceImpl">
<property name = "message" value = "Hello World!"/>
</bean>
</beans>
MessageService.java
package com.finddevguides.test;
public interface MessageService {
String getGreetingMessage();
}
MessageServiceImpl.java
package com.finddevguides.test;
public class MessageServiceImpl implements MessageService {
private String message;
public String getGreetingMessage() {
return message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
UserData.java
package com.finddevguides.test;
import java.io.Serializable;
public class UserData implements Serializable {
private static final long serialVersionUID = 1L;
private MessageService messageService;
public MessageService getMessageService() {
return messageService;
}
public void setMessageService(MessageService messageService) {
this.messageService = messageService;
}
public String getGreetingMessage() {
return messageService.getGreetingMessage();
}
}
home.xhtml
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:f = "http://java.sun.com/jsf/core"
xmlns:h = "http://java.sun.com/jsf/html">
<h:head>
<title>JSF Tutorial!</title>
</h:head>
<h:body>
<h2>Spring Integration Example</h2>
#{userData.greetingMessage}
</h:body>
</html>
すべての変更を完了したら、JSF-最初のアプリケーションの章で行ったようにアプリケーションをコンパイルして実行します。 すべてがアプリケーションで問題ない場合、次の結果が生成されます。
JSF-式言語
JSFは豊富な表現言語を提供します。 *#\ {operation-expression} *表記を使用して通常の操作を記述できます。 JSF式言語の利点の一部を次に示します。
- Beanプロパティを参照できます。Beanは、リクエスト、セッション、またはアプリケーションスコープに格納されているオブジェクト、または管理対象Beanです。
- リスト、マップ、配列などのコレクションの要素に簡単にアクセスできます。
- リクエストなどの定義済みオブジェクトに簡単にアクセスできます。
- 式言語を使用して、算術演算、論理演算、およびリレーショナル演算を実行できます。
- 自動型変換。
- NullPointerExceptionの代わりに空の文字列として欠損値を表示します。
応用例
式言語をテストするテストJSFアプリケーションを作成しましょう。
Step | Description |
---|---|
1 | Create a project with a name helloworld under a package com.finddevguides.test as explained in the JSF - First Application chapter. |
2 | Modify UserData.java under package com.finddevguides.test as explained below. |
3 | Modify home.xhtml as explained below. Keep the rest of the files unchanged. |
4 | Compile and run the application to make sure the business logic is working as per the requirements. |
5 | Finally, build the application in the form of war file and deploy it in Apache Tomcat Webserver. |
6 | Launch your web application using appropriate URL as explained below in the last step. |
UserData.java
package com.finddevguides.test;
import java.io.Serializable;
import java.util.Date;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean(name = "userData", eager = true)
@SessionScoped
public class UserData implements Serializable {
private static final long serialVersionUID = 1L;
private Date createTime = new Date();
private String message = "Hello World!";
public Date getCreateTime() {
return(createTime);
}
public String getMessage() {
return(message);
}
}
home.xhtml
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:f = "http://java.sun.com/jsf/core"
xmlns:h = "http://java.sun.com/jsf/html">
<h:head>
<title>JSF Tutorial!</title>
</h:head>
<h:body>
<h2>Expression Language Example</h2>
Creation time:
<h:outputText value = "#{userData.createTime}"/>
<br/><br/>
Message:
<h:outputText value = "#{userData.message}"/>
</h:body>
</html>
すべての変更を完了したら、JSF-最初のアプリケーションの章で行ったようにアプリケーションをコンパイルして実行します。 すべてがアプリケーションで問題ない場合、次の結果が生成されます。
JSF-国際化
国際化は、ステータスメッセージ、GUIコンポーネントラベル、通貨、日付をプログラムにハードコーディングしない手法です。 代わりに、リソースバンドルのソースコードの外部に保存され、動的に取得されます。 JSFは、リソースバンドルを処理する非常に便利な方法を提供します。
JSFアプリケーションを内部化するには、次の手順が必要です。
ステップ1:プロパティファイルを定義する
各ロケールのプロパティファイルを作成します。 名前は<file-name> _ <locale> .properties形式である必要があります。
デフォルトのロケールはファイル名で省略できます。
messages.properties
greeting = Hello World!
messages_fr.properties
greeting = Bonjour tout le monde!
ステップ2:faces-config.xmlを更新する
faces-config.xml
<application>
<locale-config>
<default-locale>en</default-locale>
<supported-locale>fr</supported-locale>
</locale-config>
<resource-bundle>
<base-name>com.finddevguides.messages</base-name>
<var>msg</var>
</resource-bundle>
</application>
ステップ3:リソースバンドル変数を使用する
home.xhtml
<h:outputText value = "#{msg['greeting']}"/>
応用例
テストJSFアプリケーションを作成して、JSFの国際化をテストしましょう。
Step | Description |
---|---|
1 | Create a project with a name helloworld under a package com.finddevguides.test as explained in the JSF - First Application chapter. |
2 | Create resources folder under src → mai folder. |
3 | Create com folder under src → main → resources folder. |
4 | Create finddevguides folder under src → main → resources → com folder. |
5 | Create messages.properties file under src → main → resources → com → finddevguides folder. Modify it as explained below. |
6 | Create messages_fr.properties file under src → main → resources → com → finddevguides folder. Modify it as explained below. |
7 | Create faces-config.xml in WEB-INFf older as explained below. |
8 | Create UserData.java under package com.finddevguides.test as explained below. |
9 | Modify home.xhtml as explained below. Keep the rest of the files unchanged. |
10 | Compile and run the application to make sure the business logic is working as per the requirements. |
11 | Finally, build the application in the form of war file and deploy it in Apache Tomcat Webserver. |
12 | Launch your web application using appropriate URL as explained below in the last step. |
messages.properties
greeting = Hello World!
messages_fr.properties
greeting = Bonjour tout le monde!
faces-config.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<faces-config
xmlns = "http://java.sun.com/xml/ns/javaee"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version = "2.0">
<application>
<locale-config>
<default-locale>en</default-locale>
<supported-locale>fr</supported-locale>
</locale-config>
<resource-bundle>
<base-name>com.finddevguides.messages</base-name>
<var>msg</var>
</resource-bundle>
</application>
</faces-config>
UserData.java
package com.finddevguides.test;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
@ManagedBean(name = "userData", eager = true)
@SessionScoped
public class UserData implements Serializable {
private static final long serialVersionUID = 1L;
private String locale;
private static Map<String,Object> countries;
static {
countries = new LinkedHashMap<String,Object>();
countries.put("English", Locale.ENGLISH);
countries.put("French", Locale.FRENCH);
}
public Map<String, Object> getCountries() {
return countries;
}
public String getLocale() {
return locale;
}
public void setLocale(String locale) {
this.locale = locale;
}
//value change event listener
public void localeChanged(ValueChangeEvent e) {
String newLocaleValue = e.getNewValue().toString();
for (Map.Entry<String, Object> entry : countries.entrySet()) {
if(entry.getValue().toString().equals(newLocaleValue)) {
FacesContext.getCurrentInstance()
.getViewRoot().setLocale((Locale)entry.getValue());
}
}
}
}
home.xhtml
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:h = "http://java.sun.com/jsf/html"
xmlns:f = "http://java.sun.com/jsf/core">
<h:head>
<title>JSF tutorial</title>
</h:head>
<h:body>
<h2>Internalization Language Example</h2>
<h:form>
<h3><h:outputText value = "#{msg['greeting']}"/></h3>
<h:panelGrid columns = "2">
Language :
<h:selectOneMenu value = "#{userData.locale}" onchange = "submit()"
valueChangeListener = "#{userData.localeChanged}">
<f:selectItems value = "#{userData.countries}"/>
</h:selectOneMenu>
</h:panelGrid>
</h:form>
</h:body>
</html>
すべての変更を完了したら、JSF-最初のアプリケーションの章で行ったようにアプリケーションをコンパイルして実行します。 すべてがアプリケーションで問題ない場合、次の結果が生成されます。
ドロップダウンから言語を変更します。 次の出力が表示されます。