Gwt-quick-guide

提供:Dev Guides
移動先:案内検索

GWT-概要

GWTとは何ですか?

Google Web Toolkit(GWT)は、* RICH Internet Applications(RIA)*を作成するための開発ツールキットです。 ここにその注目すべき機能のいくつかがあります-

  • GWTは、JAVAでクライアント側アプリケーションを作成するための開発者向けオプションを提供します。
  • GWTは、JAVAで記述されたコードをJavaScriptコードにコンパイルします。
  • GWTで記述されたアプリケーションは、ブラウザに準拠しています。 GWTは、各ブラウザーに適したJavaScriptコードを自動的に生成します。
  • GWTはオープンソースであり、完全に無料で、世界中の何千人もの開発者によって使用されています。 Apache Licenseバージョン2.0でライセンスされています。

全体的に、GWTは大規模で高性能なWebアプリケーションを構築し、メンテナンスしやすい状態に保つための*フレームワーク*です。

GWTを使用する理由

Javaベースであるため、EclipseなどのJAVA IDEを使用してGWTアプリケーションを開発できます。

開発者は、コードのオートコンプリート/リファクタリング/ナビゲーション/プロジェクト管理、および完全なデバッグ機能を提供するIDE.GWTのすべての機能を使用できます。 開発者は、Javaアプリケーションとしてクライアント側アプリケーションをデバッグできます。

  • GWTは、JunitおよびMavenとの簡単な統合を提供します。
  • 再びJavaベースであるため、GWTはJava開発者にとって学習曲線が低くなっています。
  • GWTは最適化されたJavaScriptコードを生成し、ブラウザ固有のJavaScriptコードを自分で生成します。
  • GWTが提供するウィジェットライブラリは、アプリケーションで必要なタスクのほとんどを提供します。
  • GWTは拡張可能であり、カスタムウィジェットを作成して、アプリケーションのニーズに応えることができます。

何よりも、GWTアプリケーションは、AndroidおよびiOSベースの携帯電話/タブレットを含むすべての主要なブラウザーおよびスマートフォンで実行できます。

GWTの欠点

GWTには多くの利点がありますが、次のような欠点があります-

  • Not Indexable -GWTによって生成されたWebページは、これらのアプリケーションが動的に生成されるため、検索エンジンによってインデックス付けされません。
  • 分解不可-アプリケーションユーザーがJavascriptを無効にした場合、ユーザーには基本ページのみが表示されます。
  • デザイナーのフレンドリーではありません-GWTは、後の時点でダイナミックコンテンツを挿入するためにプレースホルダーでプレーンHTMLを使用することを好むWebデザイナーには適していません

GWTコンポーネント

GWTフレームワークは、次の3つの主要な部分に分けることができます-

  • * GWT Java to JavaScriptコンパイラ*-これはGWTの最も重要な部分であり、RIAを構築するための強力なツールです。 GWTコンパイラは、Javaで記述されたすべてのアプリケーションコードをJavaScriptに変換するために使用されます。
  • * JREエミュレーションライブラリ*-Google Web Toolkitには、Javaランタイムライブラリのサブセットをエミュレートするライブラリが含まれています。 リストには、java.lang、java.lang.annotation、java.math、java.io、java.sql、java.util、およびjava.util.loggingが含まれます。
  • * GWT UI構築ライブラリ*-GWTのこの部分は、実際のUIコンポーネント、RPCサポート、履歴管理などを含む多くのサブパートで構成されています。

GWTは、ホストモードでGWTアプリケーションを実行および実行できるGWTホストWebブラウザーも提供します。このモードでは、JavaScriptにコンパイルせずに、Java仮想マシンでJavaとしてコードを実行できます。

GWT-環境設定

このチュートリアルでは、GWTフレームワークで作業を開始するための開発環境を準備する方法について説明します。 このチュートリアルでは、GWT Frameworkをセットアップする前に、マシンでJDK、Tomcat、Eclipseをセットアップする方法も説明します-

システム要件

GWTはJDK 1.6以降を必要とするため、最初の要件はJDKをマシンにインストールすることです。

JDK 1.6 or above.
Memory no minimum requirement.
Disk Space no minimum requirement.
Operating System no minimum requirement.

所定の手順に従って環境をセットアップし、GWTアプリケーション開発を開始します。

ステップ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

すべてのオペレーティングシステムの出力を確認しましょう

Sr.No. OS & Generated Output
1
  • Windows*

Javaバージョン "1.6.0_21"

Java(TM)SEランタイム環境(ビルド1.6.0_21-b07)

Java HotSpot(TM)Client VM(ビルド17.0-b17、混合モード、共有)

2

Linux

Javaバージョン "1.6.0_21"

Java(TM)SEランタイム環境(ビルド1.6.0_21-b07)

ava HotSpot(TM)Client VM(ビルド17.0-b17、混合モード、共有)

3

Mac

Javaバージョン "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がマシンにインストールされているベースディレクトリの場所を指すようにします。 例えば
Sr.No. OS & Output
1

Windows

環境変数JAVA_HOMEをC:\ Program Files \ Java \ jdk1.6.0_21に設定します

2

Linux

export JAVA_HOME =/usr/local/java-current

3

Mac

export JAVA_HOME =/Library/Java/Home

Javaコンパイラの場所をシステムパスに追加します。

Sr.No. OS & Output
1

Windows

文字列;%JAVA_HOME%\ binをシステム変数Pathの最後に追加します。

2

Linux

export PATH = $ PATH:$ JAVA_HOME/bin/

3

Mac

不要

または、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/[https://www.eclipse.org]から最新の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ホームページ

ステップ4-GWT SDKとEclipse用プラグインのインストール

リンクhttps://developers.google.com/web-toolkit/download[Plugin for Eclipse(incl。 SDK)]]を選択して、マシンにインストールされているGWT SDKおよびプラグインfor Eclipseバージョンをインストールします。

GWTプラグインのセットアップが正常に完了した後、すべてが正常であれば、以下に示すように赤い四角形でマークされた* Googleアイコン*で次の画面を表示する必要があります-

Eclipse with Google

ステップ5: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
/usr/local/apache-tomcat-6.0.33/bin/startup.sh

正常に起動した後、Tomcatに含まれているデフォルトのWebアプリケーションは、 http://localhost:8080/ にアクセスして利用できます。 すべてがうまくいけば、次の結果が表示されます-

Tomcatホームページ

Tomcatの構成と実行に関する詳細情報は、TomcatのWebサイト(https://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

GWT-アプリケーション

GWTを使用して実際の「HelloWorld」アプリケーションの作成を開始する前に、GWTアプリケーションの実際の部分が何であるかを見てみましょう-

GWTアプリケーションは、次の4つの重要な部分で構成され、そのうち最後の部分はオプションですが、最初の3つの部分は必須です。

  • モジュール記述子
  • 公共資源
  • クライアント側のコード
  • サーバーサイドコード

典型的なgwtアプリケーション HelloWord のさまざまな部分のサンプルの場所は次のようになります-

Name Location
Project root HelloWorld/
Module descriptor src/com/finddevguides/HelloWorld.gwt.xml
Public resources src/com/finddevguides/war/
Client-side code src/com/finddevguides/client/
Server-side code src/com/finddevguides/server/

モジュール記述子

モジュール記述子は、GWTアプリケーションの構成に使用されるXML形式の構成ファイルです。

モジュール記述子ファイルの拡張子は* .gwt.xmlです。*はアプリケーションの名前であり、このファイルはプロジェクトのルートに存在する必要があります。

以下は、HelloWorldアプリケーションのデフォルトモジュール記述子HelloWorld.gwt.xmlです-

<?xml version = "1.0" encoding = "utf-8"?>
<module rename-to = 'helloworld'>
   <!-- inherit the core web toolkit stuff.                        -->
   <inherits name = 'com.google.gwt.user.user'/>

   <!-- inherit the default gwt style sheet.                       -->
   <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>

   <!-- specify the app entry point class.                         -->
   <entry-point class = 'com.finddevguides.client.HelloWorld'/>

   <!-- specify the paths for translatable code                    -->
   <source path = '...'/>
   <source path = '...'/>

   <!-- specify the paths for static files like html, css etc.     -->
   <public path = '...'/>
   <public path = '...'/>

   <!-- specify the paths for external javascript files            -->
   <script src = "js-url"/>
   <script src = "js-url"/>

   <!-- specify the paths for external style sheet files            -->
   <stylesheet  src = "css-url"/>
   <stylesheet  src = "css-url"/>
</module>

以下は、モジュール記述子で使用されるさまざまなパーツに関する簡単な詳細です。

Sr.No. Nodes & Description
1

<module rename-to = "helloworld">

これにより、アプリケーションの名前が提供されます。

2

<inherits name = "logical-module-name"/>

これにより、インポートがJavaアプリケーションで行うように、アプリケーションに他のgwtモジュールが追加されます。 この方法で、任意の数のモジュールを継承できます。

3

<entry-point class = "classname"/>

これは、GWTアプリケーションのロードを開始するクラスの名前を指定します。 エントリポイントクラスはいくつでも追加でき、モジュールファイルに表示される順序で順番に呼び出されます。 したがって、最初のエントリポイントのonModuleLoad()が終了すると、次のエントリポイントがすぐに呼び出されます。

4

<source path = "path"/>

これは、GWTコンパイラがソースコンパイルを検索するソースフォルダーの名前を指定します。

5

<public path = "path"/>

パブリックパスは、CSSや画像など、GWTモジュールによって参照される静的リソースが保存されるプロジェクト内の場所です。 デフォルトのパブリックパスは、モジュールXMLファイルが保存されている下のパブリックサブディレクトリです。

6

<script src="js-url"/>

srcで指定された場所にある外部JavaScriptファイルを自動的に挿入します。

7

<stylesheet src="css-url"/>

srcで指定された場所にある外部CSSファイルを自動的に挿入します。

公共リソース

これらはすべて、ホストHTMLページ、CSS、画像など、GWTモジュールによって参照されるファイルです。

これらのリソースの場所は、モジュール構成ファイルの<public path = "path"/>要素を使用して構成できます。 デフォルトでは、モジュールXMLファイルが保存される下のパブリックサブディレクトリです。

アプリケーションをJavaScriptにコンパイルすると、パブリックパスにあるすべてのファイルがモジュールの出力ディレクトリにコピーされます。

最も重要なパブリックリソースは、実際のGWTアプリケーションを呼び出すために使用されるホストページです。 アプリケーションの一般的なHTMLホストページには、表示されるHTML本文コンテンツはまったく含まれない場合がありますが、次のように<script …​/>タグを介してGWTアプリケーションを含めることが常に期待されます。

<html>
   <head>
      <title>Hello World</title>
      <link rel = "stylesheet" href = "HelloWorld.css"/>
      <script language = "javascript" src = "helloworld/helloworld.nocache.js">
      </script>
   </head>

   <body>
      <h1>Hello World</h1>
      <p>Welcome to first GWT application</p>
   </body>
</html>

以下は、ホストページに含めたサンプルスタイルシートです-

body {
   text-align: center;
   font-family: verdana, sans-serif;
}

h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-align: center;
}

クライアント側コード

これは、アプリケーションのビジネスロジックを実装するために記述された実際のJavaコードであり、GWTコンパイラがJavaScriptに変換し、最終的にブラウザ内で実行されます。 これらのリソースの場所は、モジュール構成ファイルの<source path = "path"/>要素を使用して構成できます。

たとえば、 Entry Point コードはクライアント側コードとして使用され、その場所は<source path = "path"/>を使用して指定されます。

モジュール entry-point は、 EntryPoint に割り当て可能で、パラメーターなしで構築できるクラスです。 モジュールがロードされると、すべてのエントリポイントクラスがインスタンス化され、その* EntryPoint.onModuleLoad()*メソッドが呼び出されます。 サンプルのHelloWorldエントリポイントクラスは次のようになります-

public class HelloWorld implements EntryPoint {
   public void onModuleLoad() {
      Window.alert("Hello, World!");
   }
}

サーバー側コード

これはアプリケーションのサーバー側の部分であり、非常にオプションです。 アプリケーションでバックエンド処理を行っていない場合、この部分は必要ありませんが、バックエンドで何らかの処理が必要であり、クライアント側のアプリケーションがサーバーと対話する場合、これらのコンポーネントを開発する必要があります。

次の章では、上記のすべての概念を利用して、Eclipse IDEを使用してHelloWorldアプリケーションを作成します。

GWT-アプリケーションの作成

GWTのパワーは* Javaで記述、JavaScriptで実行*にあるため、Java IDE Eclipseを使用して例を示します。

簡単な_HelloWorld_アプリケーションから始めましょう-

ステップ1-プロジェクトの作成

最初のステップは、Eclipse IDEを使用して簡単なWebアプリケーションプロジェクトを作成することです。 オプション Google Icon Googleサービスと開発ツール>新しいWebアプリケーションプロジェクト…​ を使用してプロジェクトウィザードを起動します。 次のようにウィザードウィンドウを使用して、プロジェクトに_HelloWorld_という名前を付けます-

GWTプロジェクトの作成ウィザード

このプロジェクトでは使用していないため、[Google App Engineを使用]の選択を解除し、他のデフォルト値([*サンプルプロジェクトコードの生成]オプションを保持)をそのままにして[完了]ボタンをクリックします。

プロジェクトが正常に作成されると、プロジェクトエクスプローラーに次のコンテンツが表示されます-

GWTプロジェクト構造

ここにすべての重要なフォルダの簡単な説明があります

Sr.No. Folder & Location
1

src

ソースコード(Javaクラス)ファイル。

クライアントUI表示を担当するクライアント側固有のJavaクラスを含むクライアントフォルダー。

サーバー側の処理を担当するサーバー側のJavaクラスを含むサーバーフォルダー。

サーバーからクライアントへ、またはその逆にデータを転送するためのJavaモデルクラスを含む共有フォルダー。

HelloWorld.gwt.xml。GWTコンパイラがHelloWorldプロジェクトをコンパイルするために必要なモジュール記述子ファイルです。

2

test

テストコード(Javaクラス)のソースファイル。

gwtクライアント側コードをテストするJavaクラスを含むクライアントフォルダー。

3

war

これは最も重要な部分であり、実際にデプロイ可能なWebアプリケーションを表します。

コンパイルされたクラス、gwtライブラリ、サーブレットライブラリを含むWEB-INF。

HelloWorld.css、プロジェクトスタイルシート。

HelloWorldl、GWT UIアプリケーションを呼び出すHTMLを起動します。

ステップ2-モジュール記述子の変更:HelloWorld.gwt.xml

GWTプラグインは、デフォルトのモジュール記述子ファイル_src/com.finddevguides/HelloWorld.gwt.xml_を作成します。 この例では変更していませんが、要件に基づいて変更できます。

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to = 'helloworld'>
   <!-- Inherit the core Web Toolkit stuff.                        -->
   <inherits name = 'com.google.gwt.user.User'/>

   <!-- Inherit the default GWT style sheet.  You can change       -->
   <!-- the theme of your GWT application by uncommenting          -->
   <!-- any one of the following lines.                            -->
   <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>
   <!-- <inherits name = 'com.google.gwt.user.theme.chrome.Chrome'/> -->
   <!-- <inherits name = 'com.google.gwt.user.theme.dark.Dark'/>     -->

   <!-- Other module inherits                                      -->

   <!-- Specify the app entry point class.                         -->
   <entry-point class = 'com.finddevguides.client.HelloWorld'/>

   <!-- Specify the paths for translatable code                    -->
   <source path = 'client'/>
   <source path = 'shared'/>

</module>

手順3-スタイルシートの変更:HelloWorld.css

GWTプラグインは、デフォルトのスタイルシートファイル_war/HelloWorld.css_を作成します。 このファイルを修正して、サンプルを最も単純なレベルの理解に保つようにしましょう-

body {
   text-align: center;
   font-family: verdana, sans-serif;
}

h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-align: center;
}

手順4-ホストファイルの変更:HelloWorldl

GWTプラグインは、デフォルトのHTMLホストファイル_war/HelloWorldl_を作成します。 このファイルを修正して、サンプルを最も単純なレベルの理解に保つようにしましょう-

<html>
   <head>
      <title>Hello World</title>
      <link rel = "stylesheet" href = "HelloWorld.css"/>
      <script language = "javascript" src = "helloworld/helloworld.nocache.js">
      </script>
   </head>

   <body>
      <h1>Hello World</h1>
      <p>Welcome to first GWT application</p>
   </body>
</html>

同じソースディレクトリにHTML、CSS、画像などの静的ファイルを作成するか、さらにサブディレクトリを作成してそれらのサブディレクトリにファイルを移動し、アプリケーションのモジュール記述子でこれらのサブディレクトリを構成できます。

手順5-エントリポイントの変更:HelloWorld.java

GWTプラグインは、アプリケーションのエントリポイントを保持するデフォルトのJavaファイル_src/com.finddevguides/HelloWorld.java_を作成します。

このファイルを変更して、「Hello、World!」を表示しましょう。

package com.finddevguides.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.Window;

public class HelloWorld implements EntryPoint {
   public void onModuleLoad() {
      Window.alert("Hello, World!");
   }
}

同じソースディレクトリにさらにJavaファイルを作成して、エントリポイントを定義するか、ヘルパールーチンを定義できます。

ステップ6-アプリケーションのコンパイル

すべての変更が完了したら、プロジェクトをコンパイルします。 オプション GoogleアイコンGoogleサービスおよび開発ツール> GWTコンパイルプロジェクト…​ を使用して、以下に示すようにGWTコンパイルダイアログボックスを起動します-

GWTプロジェクトのコンパイルウィザード

デフォルト値をそのままにして、「コンパイル」ボタンをクリックします。 すべてがうまくいくと、Eclipseコンソールに次の出力が表示されます。

Compiling module com.finddevguides.HelloWorld
   Compiling 6 permutations
      Compiling permutation 0...
      Compiling permutation 1...
      Compiling permutation 2...
      Compiling permutation 3...
      Compiling permutation 4...
      Compiling permutation 5...
   Compile of permutations succeeded
Linking into C:\workspace\HelloWorld\war\helloworld
   Link succeeded
   Compilation succeeded -- 33.029s

ステップ7-アプリケーションの実行

次に、アプリケーションの実行をクリックして、アプリケーションを実行し、 HelloWorld アプリケーションを選択してアプリケーションを実行します。

GWT実行ボタン

すべてが正常な場合、以下に示すURLを含むEclipseでGWT開発モードがアクティブになっている必要があります。 URLをダブルクリックしてGWTアプリケーションを開きます。

GWTアプリケーションの実行

開発モードでアプリケーションを実行しているため、ブラウザにGWTプラグインをインストールする必要があります。 画面上の指示に従ってプラグインをインストールするだけです。

既にブラウザにGWTプラグインが設定されている場合は、次の出力が表示されるはずです。

GWTアプリケーション結果

おめでとうございます。 Google Web Toolkit(GWT)を使用して最初のアプリケーションを実装しました。

GWT-アプリケーションのデプロイ

このチュートリアルでは、アプリケーション "war" ファイルを作成する方法と、それをApache Tomcat Webseverルートにデプロイする方法を説明します。

この簡単な例を理解していれば、同じ手順に従って複雑なGWTアプリケーションをデプロイすることもできます。

GWTプラグインとともにEclipse IDEを使用し、次の手順に従ってGWTアプリケーションを作成します。

Step

説明

1

_GWT-アプリケーションの作成_の章の説明に従って、_com.finddevguides_パッケージの下に_HelloWorld_という名前のプロジェクトを作成します。

2

以下で説明するように、HelloWorld.gwt.xml _、 HelloWorld.css HelloWorldl_、および_HelloWorld.java_を変更します。 残りのファイルは変更しないでください。

3

アプリケーションをコンパイルして実行し、要件に従ってビジネスロジックが機能していることを確認します。

4

最後に、アプリケーションのwarフォルダーのコンテンツをwarファイルの形式で圧縮し、Apache Tomcat Webserverにデプロイします。

5

以下の最後の手順で説明するように、適切なURLを使用してWebアプリケーションを起動します。

以下は、変更されたモジュール記述子 src/com.finddevguides/HelloWorld.gwt.xml の内容です。

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to = 'helloworld'>
   <!-- Inherit the core Web Toolkit stuff.                        -->
   <inherits name = 'com.google.gwt.user.User'/>

   <!-- Inherit the default GWT style sheet.                       -->
   <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>

   <!-- Specify the app entry point class.                         -->
   <entry-point class = 'com.finddevguides.client.HelloWorld'/>

   <!-- Specify the paths for translatable code                    -->
   <source path = 'client'/>
   <source path = 'shared'/>

</module>

以下は、変更されたスタイルシートファイル war/HelloWorld.css の内容です。

body {
   text-align: center;
   font-family: verdana, sans-serif;
}

h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-align: center;
}

以下は、変更されたHTMLホストファイル war/HelloWorldl の内容です。

<html>
   <head>
      <title>Hello World</title>
      <link rel = "stylesheet" href = "HelloWorld.css"/>
      <script language = "javascript" src = "helloworld/helloworld.nocache.js">
      </script>
   </head>

   <body>
      <h1>Hello World</h1>
      <div id = "gwtContainer"></div>
   </body>
</html>

前の例からHTMLを少し変更しました。 ここで、プレースホルダ<div> …​ </div>を作成しました。ここで、エントリポイントJavaクラスを使用してコンテンツを挿入します。 それでは、Javaファイル src/com.finddevguides/HelloWorld.java の内容を以下に示します。

package com.finddevguides.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootPanel;

public class HelloWorld implements EntryPoint {
   public void onModuleLoad() {
      HTML html = new HTML("<p>Welcome to GWT application</p>");

      RootPanel.get("gwtContainer").add(html);
   }
}

ここでは、基本的なwidgest HTMLを作成し、id = "gwtContainer"を持つdivタグ内に追加しました。 今後の章では、さまざまなGWTウィジェットについて学習します。

すべての変更が完了したら、link:/gwt/gwt_create_application [GWT-アプリケーションの作成]の章で行ったように、アプリケーションをコンパイルして開発モードで実行します。 すべてがあなたのアプリケーションでうまくいけば、これは次の結果を生成します-

GWTアプリケーション結果2

WARファイルを作成する

これでアプリケーションが正常に動作し、warファイルとしてエクスポートする準備が整いました。

次の手順に従ってください-

  • プロジェクトの war ディレクトリに移動します C:\ workspace \ HelloWorld \ war
  • warディレクトリ内で使用可能なすべてのファイルとフォルダーを選択します。
  • 選択したすべてのファイルとフォルダーを_HelloWorld.zip_というファイルに圧縮します。
  • _HelloWorld.zip_の名前を_HelloWorld.war_に変更します。

WARファイルを展開する

  • Tomcatサーバーを停止します。
  • _HelloWorld.war_ファイルを* tomcatインストールディレクトリ> webappsフォルダーにコピーします。*
  • Tomcatサーバーを起動します。
  • webappsディレクトリ内を見てください。 helloworld フォルダーが作成されているはずです。
  • これで、HelloWorld.warがTomcat Webサーバールートに正常にデプロイされました。

アプリケーションを実行

WebブラウザーでURLを入力します: http://localhost:8080/HelloWorld アプリケーションを起動します

サーバー名(localhost)とポート(8080)は、Tomcatの構成によって異なる場合があります。

GWTアプリケーション結果3

GWT-CSSを使用したスタイル

GWTウィジェットは、視覚的なスタイリングをカスケードスタイルシート(CSS)に依存しています。 デフォルトでは、各コンポーネントのクラス名は gwt- <classname> です。

たとえば、ボタンウィジェットのデフォルトスタイルは_gwt-Button_であり、同様の方法でTextBox widgestのデフォルトスタイルは_gwt-TextBox_です。

すべてのボタンとテキストボックスに大きなフォントを設定するには、アプリケーションのCSSファイルに次のルールを追加します

.gwt-Button  { font-size: 150%; }

.gwt-TextBox { font-size: 150%; }

デフォルトでは、ブラウザもGWTもウィジェットのデフォルトの id 属性を作成しません。 CSSで使用できる要素の一意のIDを明示的に作成する必要があります。 id my-button-id を持つ特定のボタンに大きなフォントを与えるには、アプリケーションのCSSファイルに次のルールを置くことができます-

#my-button-id { font-size: 150%; }

GWTウィジェットのIDを設定するには、そのDOM要素を取得し、次のようにID属性を設定します-

Button b = new Button();
DOM.setElementAttribute(b.getElement(), "id", "my-button-id")

CSSスタイリングAPI

GWTウィジェットのCSS設定を変更するために使用できるAPIは多数あります。 以下は、GWTを使用した日々のWebプログラミングで役立ついくつかの重要なAPIです。

Sr.No. API & Description
1

public void setStyleName(java.lang.String style)

このメソッドは、既存のスタイルをクリアし、_style_を使用して提供される新しいCSSクラスにウィジェットスタイルを設定します。

2

public void addStyleName(java.lang.String style)

このメソッドは、二次または従属スタイル名をウィジェットに追加します。 二次スタイル名は追加のスタイル名です。したがって、以前のスタイル名が適用されていた場合、それらは保持されます。

3

public void removeStyleName(java.lang.String style)

このメソッドは、指定されたスタイルをウィジェットから削除し、ウィジェットに関連付けられている他のスタイルを残します。

4

public java.lang.String getStyleName()

このメソッドは、スペースで区切られたリストとして、オブジェクトのすべてのスタイル名を取得します。

5

public void setStylePrimaryName(java.lang.String style)

このメソッドは、オブジェクトのプライマリスタイル名を設定し、すべての依存スタイル名を更新します。

たとえば、テキストに適用する2つの新しいスタイルを定義しましょう-

.gwt-Big-Text {
   font-size:150%;
}

.gwt-Small-Text {
   font-size:75%;
}

.gwt-Red-Text {
   color:red;
}

これで、_setStyleName(Style)_を使用して、デフォルト設定を新しい設定に変更できます。 以下のルールを適用すると、テキストのフォントが大きくなります

txtWidget.setStyleName("gwt-Big-Text");

同じウィジェットにセカンダリCSSルールを適用して、次のように色を変更できます-

txtWidget.addStyleName("gwt-Red-Text");

上記の方法を使用すると、ウィジェットに適用するスタイルを好きなだけ追加できます。 ボタンウィジェットから最初のスタイルを削除しても、テキストには2番目のスタイルが残ります。

txtWidget.removeStyleName("gwt-Big-Text");

プライマリスタイルとセカンダリスタイル

デフォルトでは、ウィジェットの_primary style_名は、そのウィジェットクラスのデフォルトのスタイル名になります(たとえば、ボタンウィジェットの場合は_gwt-Button_)。 AddStyleName()メソッドを使用してスタイル名を追加および削除する場合、これらのスタイルはセカンダリスタイルと呼ばれます。

ウィジェットの最終的な外観は、ウィジェットに追加されたすべてのセカンダリスタイルとそのプライマリスタイルの合計によって決まります。 _setStylePrimaryName(String)_メソッドを使用して、ウィジェットのプライマリスタイルを設定します。 説明のために、Labelウィジェットがあるとします。 私たちのCSSファイルでは、次のルールが定義されています-

.MyText {
   color: blue;
}

.BigText {
   font-size: large;
}

.LoudText {
   font-weight:  bold;
}

特定のラベルウィジェットに常に青色のテキストを表示し、場合によっては、強調のために大きく太字のフォントを使用するとします。

私たちはこのようなことをすることができます-

//set up our primary style
Label someText = new Label();
someText.setStylePrimaryName("MyText");
...

//later on, to really grab the user's attention
someText.addStyleName("BigText");
someText.addStyleName("LoudText");
...

//after the crisis is over
someText.removeStyleName("BigText");
someText.removeStyleName("LoudText");

CSSファイルの関連付け

CSSファイルをモジュールに関連付けるには、複数のアプローチがあります。 現代のGWTアプリケーションは通常、CssResourceとUiBinderの組み合わせを使用します。 この例では、最初のアプローチのみを使用しています。

  • ホストHTMLページで<link>タグを使用します。
  • モジュールXMLファイルで<stylesheet>要素を使用します。
  • ClientBundle に含まれる CssResource を使用します。
  • UiBinder テンプレートでインライン<ui:style>要素を使用します。

GWT CSSの例

この例では、GWT widgestにさまざまなCSSルールを適用する簡単な手順を紹介します。 GWTプラグインとともにEclipse IDEを使用し、次の手順に従ってGWTアプリケーションを作成します。

Step Description
1 Create a project with a name HelloWorld under a package com.finddevguides as explained in the GWT - Create Application chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorldl and HelloWorld.java as explained below. Keep rest of the files unchanged.
3 Compile and run the application to verify the result of the implemented logic.

以下は、変更されたモジュール記述子 src/com.finddevguides/HelloWorld.gwt.xml の内容です。

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to = 'helloworld'>
   <!-- Inherit the core Web Toolkit stuff.                        -->
   <inherits name = 'com.google.gwt.user.User'/>

   <!-- Inherit the default GWT style sheet.                       -->
   <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>

   <!-- Specify the app entry point class.                         -->
   <entry-point class = 'com.finddevguides.client.HelloWorld'/>

   <!-- Specify the paths for translatable code                    -->
   <source path = 'client'/>
   <source path = 'shared'/>

</module>

以下は、変更されたスタイルシートファイル war/HelloWorld.css の内容です。

body {
   text-align: center;
   font-family: verdana, sans-serif;
}

h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-align: center;
}

.gwt-Button {
   font-size: 150%;
   font-weight: bold;
   width:100px;
   height:100px;
}

.gwt-Big-Text {
   font-size:150%;
}

.gwt-Small-Text {
   font-size:75%;
}

以下は、2つのボタンに対応するように変更されたHTMLホストファイル war/HelloWorldl の内容です。

<html>
   <head>
      <title>Hello World</title>
      <link rel = "stylesheet" href = "HelloWorld.css"/>
      <script language = "javascript" src = "helloworld/helloworld.nocache.js">
      </script>
   </head>

   <body>
      <div id = "mytext"><h1>Hello, World!</h1></div>
      <div id = "gwtGreenButton"></div>
      <div id = "gwtRedButton"></div>
   </body>
</html>

HTMLに2つのボタンを追加し、カスタムCSSスタイルを適用するJavaファイル src/com.finddevguides/HelloWorld.java のコンテンツを見てみましょう。

package com.finddevguides.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootPanel;

public class HelloWorld implements EntryPoint {
   public void onModuleLoad() {

  //add button to change font to big when clicked.
   Button Btn1 = new Button("Big Text");
   Btn1.addClickHandler(new ClickHandler() {
      public void onClick(ClickEvent event) {
         RootPanel.get("mytext").setStyleName("gwt-Big-Text");
      }
   });

  //add button to change font to small when clicked.
   Button Btn2 = new Button("Small Text");
   Btn2.addClickHandler(new ClickHandler() {
      public void onClick(ClickEvent event) {
         RootPanel.get("mytext").setStyleName("gwt-Small-Text");
      }
   });

   RootPanel.get("gwtGreenButton").add(Btn1);
   RootPanel.get("gwtRedButton").add(Btn2);
   }
}

すべての変更が完了したら、link:/gwt/gwt_create_application [GWT-アプリケーションの作成]の章で行ったように、アプリケーションをコンパイルして開発モードで実行します。 すべてがあなたのアプリケーションでうまくいけば、これは次の結果を生成します-

GWT CSSアプリケーション結果

表示された2つのボタンをクリックして、「Hello、World!」を確認してください。 2つのボタンをクリックしたときにフォントを変更し続けるテキスト。

GWT-基本的なウィジェット

すべてのユーザーインターフェイスは、次の3つの主要な側面を考慮します-

  • * UI要素*-これらは、ユーザーが最終的に表示して対話するコア視覚要素です。 GWTは、このチュートリアルで扱う基本から複雑なものまでさまざまな、広く使用されている一般的な要素の膨大なリストを提供します。
  • レイアウト-UI要素を画面上で整理する方法を定義し、GUI(グラフィカルユーザーインターフェイス)に最終的なルックアンドフィールを提供します。 この部分については、レイアウトの章で説明します。
  • 動作-これらは、ユーザーがUI要素と対話するときに発生するイベントです。 この部分については、イベント処理の章で説明します。

GWT UI要素

GWTライブラリは、明確に定義されたクラス階層のクラスを提供して、複雑なWebベースのユーザーインターフェイスを作成します。 このコンポーネント階層のすべてのクラスは、以下に示すように UIObject ベースクラスから派生しています-

GWTコンポーネント

すべてのBasic UIウィジェットは、Widgetクラスからプロパティを継承し、WidgetクラスはUIObjectからプロパティを継承します。 ツリーとメニューについては、複雑なウィジェットのチュートリアルで説明します。

Sr.No. Widget & Description
1

GWT UIObject Class

このウィジェットには、<div>要素を使用してHTMLとして解釈されないテキストが含まれているため、ブロックレイアウトで表示されます。

2

GWT Widget Class

このウィジェットにはHTMLテキストを含めることができ、<div>要素を使用してhtmlコンテンツを表示するため、ブロックレイアウトで表示されます。

基本的なウィジェット

以下は、いくつかの重要な_基本的なウィジェット_です-

Sr.No. Widget & Description
1

Label

このウィジェットには、<div>要素を使用してHTMLとして解釈されないテキストが含まれているため、ブロックレイアウトで表示されます。

2

HTML

このウィジェットにはHTMLテキストを含めることができ、<div>要素を使用してhtmlコンテンツを表示するため、ブロックレイアウトで表示されます。

3

Image

このウィジェットは、指定されたURLの画像を表示します。

4

Anchor

このウィジェットは、単純な<a>要素を表します。

GWT-フォームウィジェット

フォームウィジェットを使用すると、ユーザーはデータを入力し、アプリケーションとの対話機能を提供できます。 すべてのフォームウィジェットは、ウィジェットクラスからプロパティを継承し、ウィジェットクラスはUIObjectクラスおよびWigdetクラスからプロパティを継承します。

Sr.No. Widget & Description
1

GWT UIObject Class

このウィジェットには、<div>要素を使用してHTMLとして解釈されないテキストが含まれているため、ブロックレイアウトで表示されます。

2

GWT Widget Class

このウィジェットにはHTMLテキストを含めることができ、<div>要素を使用してhtmlコンテンツを表示するため、ブロックレイアウトで表示されます。

フォームウィジェット

以下は、いくつかの重要な_Form Widgets_です-

Sr.No. Widget & Description
1

Button

このウィジェットは、標準のプッシュボタンを表します。

2

PushButton

このウィジェットは、カスタムスタイルの通常のプッシュボタンを表します。

3

ToggleButton

このウィジェットは、ユーザーがアップ状態とダウン状態を切り替えることができるスタイリッシュなステートフルボタンを表します。

4

CheckBox

このウィジェットは、標準のチェックボックスウィジェットを表します。 このクラスは、RadioButtonの基本クラスとしても機能します。

5

RadioButton

このウィジェットは、相互に排他的な選択ラジオボタンウィジェットを表します。

6

ListBox

このウィジェットは、リストボックスまたはドロップダウンリストとして、ユーザーに対する選択肢のリストを表します。

7

SuggestBox

このウィジェットは、ユーザーの入力に一致する事前に構成された選択セットを表示するテキストボックスまたはテキスト領域を表します。 各SuggestBoxは、単一のSuggestOracleに関連付けられています。 SuggestOracleは、特定のクエリ文字列を指定して一連の選択を提供するために使用されます。

8

TextBox

このウィジェットは、1行のテキストボックスを表します。

9

PasswordTextBox

このウィジェットは、盗聴を防ぐために入力を視覚的にマスクするテキストボックスを表します。

10

TextArea

このウィジェットは、複数行のテキストを入力できるテキストボックスを表します。

11

RichTextArea

このウィジェットは、複雑なスタイル設定と書式設定を可能にするリッチテキストエディターを表します。

12

FileUpload

このウィジェットは、HTML <input type = 'file'>要素をラップします。

13

Hidden

このウィジェットは、HTMLフォームの非表示フィールドを再設定します。

GWT-複雑なウィジェット

「複雑なウィジェット」により、ユーザーはアプリケーションとの高度な対話機能を使用できます。 すべてのComplexウィジェットは、Widgetクラスからプロパティを継承し、WidgetクラスはUIObjectからプロパティを継承します。

Sr.No. Widget & Description
1

GWT UIObject Class

このウィジェットには、<div>要素を使用してHTMLとして解釈されないテキストが含まれているため、ブロックレイアウトで表示されます。

2

GWT Widget Class

このウィジェットにはHTMLテキストを含めることができ、<div>要素を使用してhtmlコンテンツを表示するため、ブロックレイアウトで表示されます。

複雑なウィジェット

以下は、いくつかの重要な複雑なウィジェットです-

Sr.No. Widget & Description
1

Tree

このウィジェットは、標準の階層ツリーウィジェットを表します。 ツリーには、ユーザーが開いたり、閉じたり、選択したりできるTreeItemsの階層が含まれています。

2

MenuBar

このウィジェットは、標準のメニューバーウィジェットを表します。 メニューバーには、任意の数のメニュー項目を含めることができます。各メニュー項目は、コマンドを起動するか、カスケードメニューバーを開くことができます。

3

DatePicker

このウィジェットは、標準のGWT日付ピッカーを表します。

4

CellTree

このウィジェットは、ツリーのビューを表します。 このウィジェットは標準モードでのみ機能します。標準モードでは、ウィジェットを実行するHTMLページに<!DOCTYPE>宣言が明示的に必要です。

5

CellList

このウィジェットは、セルの単一列リストを表します。

6

CellTable

このウィジェットは、ページングと列をサポートする表形式のビューを表します。

7

CellBrowser

このウィジェットは、レベルごとに1つのノードのみが一度に開くことができるツリーの*閲覧可能な*ビューを表します。 このウィジェットは標準モードでのみ機能します。標準モードでは、ウィジェットを実行するHTMLページに<!DOCTYPE>宣言が明示的に必要です。

GWT-レイアウトパネル

レイアウトパネルには他のウィジェットを含めることができます。 これらのパネルは、ウィジェットをユーザーインターフェイスに表示する方法を制御します。 すべてのPanelウィジェットはPanelクラスからプロパティを継承し、PanelクラスはWidgetクラスからプロパティを継承し、さらにUIObjectクラスからプロパティを継承します。

Sr.No. Widget & Description
1

GWT UIObject Class

このウィジェットには、<div>要素を使用してHTMLとして解釈されないテキストが含まれているため、ブロックレイアウトで表示されます。

2

GWT Widget Class

このウィジェットにはHTMLテキストを含めることができ、<div>要素を使用してhtmlコンテンツを表示するため、ブロックレイアウトで表示されます。

3

GWT Panel Class

これは、他のウィジェットを含むことができるウィジェットであるすべてのパネルの抽象基本クラスです。

レイアウトパネル

以下はいくつかの重要な_レイアウトパネル_です-

Sr.No. Widget & Description
1

FlowPanel

このウィジェットは、デフォルトのHTMLレイアウト動作を使用して子ウィジェットをフォーマットするパネルを表します。

2

HorizontalPanel

このウィジェットは、すべてのウィジェットを単一の水平列に配置するパネルを表します。

3

VerticalPanel

このウィジェットは、すべてのウィジェットを単一の垂直列に配置するパネルを表します。

4

HorizontalSplitPanel

このウィジェットは、2つのウィジェットを1つの水平方向の行に配置するパネルを表し、ユーザーは2つのウィジェットのそれぞれに専用の幅の割合をインタラクティブに変更できます。 Horizo​​ntalSplitPanelに含まれるウィジェットは、必要なときにスクロールバーで自動的に装飾されます。

5

VerticalSplitPanel

このウィジェットは、2つのウィジェットを1つの垂直列に配置するAパネルを表し、ユーザーは2つのウィジェットのそれぞれに専用の高さの割合を対話的に変更できます。 VertialSplitPanelに含まれるウィジェットは、必要に応じてスクロールバーで自動的に装飾されます。

6

FlexTable

このウィジェットは、オンデマンドでセルを作成する柔軟なテーブルを表します。 ギザギザにすることができ(つまり、各行に異なる数のセルを含めることができます)、個々のセルを複数の行または列にまたがるように設定できます。

7

Grid

このウィジェットは、セル内にテキスト、html、または子ウィジェットを含むことができる長方形のグリッドを表します。 行と列の目的の数に明示的にサイズ変更する必要があります。

8

DeckPanel

すべての子ウィジェットを「デッキ」に表示するパネル。一度に1つしか表示できません。 TabPanelによって使用されます。

9

DockPanel

このウィジェットは、子ウィジェットをその外側の端に「ドッキング」して配置し、最後のウィジェットが中央の残りのスペースを占有できるようにするパネルを表します。

10

HTMLPanel

このウィジェットは、HTMLを含むパネルを表し、HTML内の識別された要素に子ウィジェットを添付できます。

11

TabPanel

このウィジェットは、タブ付きのページセットを表すパネルを表し、各ページには別のウィジェットが含まれています。 ユーザーが関連付けられているさまざまなタブを選択すると、その子ウィジェットが表示されます。 タブには任意のHTMLを含めることができます。

12

Composite

このウィジェットは、別のウィジェットをラップして、ラップされたウィジェットのメソッドを隠すことができるウィジェットのタイプを表します。 パネルに追加すると、コンポジットは、ラップするウィジェットが追加されたかのように動作します。

13

SimplePanel

このウィジェットは、1つのウィジェットのみを含むパネルの基本クラスを表します。

14

ScrollPanel

このウィジェットは、スクロール可能な領域にコンテンツをラップするシンプルなパネルを表します

15

FocusPanel

このウィジェットは、コンテンツをフォーカス可能にするシンプルなパネルを表し、マウスとキーボードのイベントをキャッチする機能を追加します。

16

FormPanel

このウィジェットは、コンテンツをHTML <FORM>要素でラップするパネルを表します。

17

PopupPanel

このウィジェットは、他のウィジェットの上に*ポップアップ*できるパネルを表します。 ブラウザのクライアント領域(および以前に作成されたポップアップ)をオーバーレイします。

18

DialogBox

このウィジェットは、上部にキャプション領域があり、ユーザーがドラッグできるポップアップのフォームを表します。 PopupPanelとは異なり、PopupPanel.setWidth(String)およびPopupPanel.setHeight(String)を呼び出すと、ウィジェットがまだ追加されていない場合でも、ダイアログボックス自体の幅と高さが設定されます。

GWT-イベント処理

GWTは、Java AWTまたはSWINGユーザーインターフェイスフレームワークに類似したイベントハンドラモデルを提供します。

  • リスナーインターフェイスは、ウィジェットがイベントをアナウンスするために呼び出す1つ以上のメソッドを定義します。 GWTは、さまざまなイベントに対応するインターフェースのリストを提供します。
  • 特定のタイプのイベントを受信したいクラスは、関連付けられたハンドラーインターフェースを実装し、それからウィジェットへの参照を渡して、一連のイベントをサブスクライブします。

たとえば、 Button クラスは* clickイベント*を発行するため、 Click イベントを処理する_ClickHandler_を実装するクラスを作成する必要があります。

イベントハンドラーインターフェイス

すべてのGWTイベントハンドラーは_EventHandler_インターフェースから拡張されており、各ハンドラーには単一の引数を持つ単一のメソッドしかありません。 この引数は、常に関連するイベントタイプのオブジェクトです。 各 event オブジェクトには、渡されたイベントオブジェクトを操作するためのいくつかのメソッドがあります。 たとえばクリックイベントの場合、次のようにハンドラを記述する必要があります-

/**
 *create a custom click handler which will call
* onClick method when button is clicked.
 */
public class MyClickHandler implements ClickHandler {
   @Override
   public void onClick(ClickEvent event) {
      Window.alert("Hello World!");
   }
}

これで、クリックイベントの受信を希望するクラスは、* addClickHandler()*を呼び出して、次のようにイベントハンドラを登録します。

/**
 *create button and attach click handler
*/
Button button = new Button("Click Me!");
button.addClickHandler(new MyClickHandler());

イベントタイプをサポートする各ウィジェットには、HandlerRegistration add * Foo * Handler(* Foo * Event)という形式のメソッドがあります。 Foo は、Click、Error、KeyPressなどの実際のイベントです。

以下は、重要なGWTイベントハンドラーと関連イベントおよびハンドラー登録メソッドのリストです-

Sr.No. Event Interface Event Method & Description
1 Before Selection Handler<I>

void on Before Selection (Before Selection Event<I> event);

BeforeSelectionEventが発生したときに呼び出されます。

2 BlurHandler

void on Blur(Blur Event event);

ぼかしイベントが発生したときに呼び出されます。

3 ChangeHandler

void on Change(ChangeEvent event);

変更イベントが発生したときに呼び出されます。

4 ClickHandler

void on Click(ClickEvent event);

ネイティブクリックイベントが発生したときに呼び出されます。

5 CloseHandler<T>

void on Close(CloseEvent<T> event);

CloseEventが発生したときに呼び出されます。

6 Context Menu Handler

void on Context Menu(Context Menu Event event);

ネイティブコンテキストメニューイベントが発生したときに呼び出されます。

7 Double Click Handler

void on Double Click(Double Click Event event);

ダブルクリックイベントが発生したときに呼び出されます。

8 Error Handler

void on Error(Error Event event);

エラーイベントが発生したときに呼び出されます。

9 Focus Handler

void on Focus(Focus Event event);

フォーカスイベントが発生したときに呼び出されます。

10 Form Panel.Submit Complete Handler

void on Submit Complete(Form Panel.Submit Complete Event event);

フォームが正常に送信されたときに発生します。

11 FormPanel.SubmitHandler

void on Submit(Form Panel.Submit Event event);

フォームが送信されたときに発生します。

12 Key Down Handler

void on Key Down(Key Down Event event);

KeyDownEventが発生したときに呼び出されます。

13 KeyPressHandler

void on KeyPress(KeyPressEvent event);

KeyPressEventが発生したときに呼び出されます。

14 KeyUpHandler

void on KeyUp(KeyUpEvent event);

KeyUpEventが発生したときに呼び出されます。

15 LoadHandler

void on Load(LoadEvent event);

LoadEventが発生したときに呼び出されます。

16 MouseDownHandler

void on MouseDown(MouseDownEvent event);

MouseDownが発生したときに呼び出されます。

17 MouseMoveHandler

void on MouseMove(MouseMoveEvent event);

MouseMoveEventが発生したときに呼び出されます。

18 MouseOutHandler

void on MouseOut(MouseOutEvent event);

MouseOutEventが発生したときに呼び出されます。

19 MouseOverHandler

void on MouseOver(MouseOverEvent event);

MouseOverEventが発生したときに呼び出されます。

20 MouseUpHandler

void on MouseUp(MouseUpEvent event);

MouseUpEventが発生したときに呼び出されます。

21 MouseWheelHandler

void on MouseWheel(MouseWheelEvent event);

MouseWheelEventが発生したときに呼び出されます。

22 ResizeHandler

void on Resize(ResizeEvent event);

ウィジェットのサイズが変更されたときに発生します。

23 ScrollHandler

void on Scroll(ScrollEvent event);

ScrollEventが発生したときに呼び出されます。

24 SelectionHandler<I>

void on Selection(SelectionEvent<I> event);

SelectionEventが発生したときに呼び出されます。

25 ValueChangeHandler<I>

void on ValueChange(ValueChangeEvent<I> event);

ValueChangeEventが発生したときに呼び出されます。

26 Window.ClosingHandler

void on WindowClosing(Window.ClosingEvent event);

ブラウザウィンドウが閉じるか、別のサイトに移動する直前に発生します。

27 Window.ScrollHandler

void on WindowScroll(Window.ScrollEvent event);

ブラウザウィンドウがスクロールされたときに発生します。

イベントメソッド

前述のように、各ハンドラには、_void onClick(ClickEvent event)_や_void onKeyDown(KeyDownEvent event)_など、イベントオブジェクトを保持する単一の引数を持つ単一のメソッドがあります。 _ClickEvent_や_KeyDownEvent_などのイベントオブジェクトには、以下にリストされているいくつかの一般的なメソッドがあります-

Sr.No. Method & Description
1 protected void dispatch(ClickHandler handler) This method Should only be called by HandlerManager
2 DomEvent.Type <FooHandler> getAssociatedType() *This method returns the type used to register Foo* event.
3 static DomEvent.Type<FooHandler> getType() *This method gets the event type associated with Foo* events.
4 public java.lang.Object getSource() This method returns the source that last fired this event.
5 protected final boolean isLive() This method returns whether the event is live.
6 protected void kill() This method kills the event

この例では、GWTでの Click イベントおよび KeyDown イベント処理の使用方法を示す簡単な手順を紹介します。 次の手順に従って、_GWTで作成したGWTアプリケーションを更新します-アプリケーションの作成_の章-

Step Description
1 Create a project with a name HelloWorld under a package com.finddevguides as explained in the GWT - Create Application chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorldl and HelloWorld.java as explained below. Keep rest of the files unchanged.
3 Compile and run the application to verify the result of the implemented logic.

以下は、変更されたモジュール記述子 src/com.finddevguides/HelloWorld.gwt.xml の内容です。

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to = 'helloworld'>
   <!-- Inherit the core Web Toolkit stuff.                        -->
   <inherits name = 'com.google.gwt.user.User'/>

   <!-- Inherit the default GWT style sheet.                       -->
   <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>

   <!-- Specify the app entry point class.                         -->
   <entry-point class = 'com.finddevguides.client.HelloWorld'/>

   <!-- Specify the paths for translatable code                    -->
   <source path = 'client'/>
   <source path = 'shared'/>

</module>

以下は、変更されたスタイルシートファイル war/HelloWorld.css の内容です。

body {
   text-align: center;
   font-family: verdana, sans-serif;
}

h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-align: center;
}

以下は、変更されたHTMLホストファイル war/HelloWorldl の内容です。

<html>
   <head>
      <title>Hello World</title>
      <link rel = "stylesheet" href = "HelloWorld.css"/>
      <script language = "javascript" src = "helloworld/helloworld.nocache.js">
      </script>
   </head>

   <body>
      <h1>Event Handling Demonstration</h1>
      <div id = "gwtContainer"></div>
   </body>
</html>

GWTでのイベント処理の使用法を示すJavaファイル src/com.finddevguides/HelloWorld.java の内容を見てみましょう。

package com.finddevguides.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class HelloWorld implements EntryPoint {
   public void onModuleLoad() {
     /**
 *create textbox and attach key down handler
      */
      TextBox textBox = new TextBox();
      textBox.addKeyDownHandler(new MyKeyDownHandler());

     /*
 *create button and attach click handler
      */
      Button button = new Button("Click Me!");
      button.addClickHandler(new MyClickHandler());

      VerticalPanel panel = new VerticalPanel();
      panel.setSpacing(10);
      panel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
      panel.setSize("300", "100");
      panel.add(textBox);
      panel.add(button);

      DecoratorPanel decoratorPanel = new DecoratorPanel();
      decoratorPanel.add(panel);
      RootPanel.get("gwtContainer").add(decoratorPanel);
   }

  /* *
   * create a custom click handler which will call
 *onClick method when button is clicked.
   */
   private class MyClickHandler implements ClickHandler {
      @Override
      public void onClick(ClickEvent event) {
         Window.alert("Hello World!");
      }
   }

  /**
 *create a custom key down handler which will call
   * onKeyDown method when a key is down in textbox.
    */
   private class MyKeyDownHandler implements KeyDownHandler {
      @Override
      public void onKeyDown(KeyDownEvent event) {
         if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER){
            Window.alert(((TextBox)event.getSource()).getValue());
         }
      }
   }
}

すべての変更が完了したら、link:/gwt/gwt_create_application [GWT-アプリケーションの作成]の章で行ったように、アプリケーションをコンパイルして開発モードで実行します。 すべてがあなたのアプリケーションでうまくいけば、これは次の結果を生成します-

GWTイベント処理

GWT-カスタムウィジェット

GWTは、カスタムユーザーインターフェイス要素を作成する3つの方法を提供します。 従うべき3つの一般的な戦略があります-

  • 複合クラスを拡張してウィジェットを作成-これは、カスタムウィジェットを作成する最も一般的で簡単な方法です。 ここでは、既存のウィジェットを使用して、カスタムプロパティを持つ複合ビューを作成できます。
  • * JAVAでGWT DOM APIを使用してウィジェットを作成します*-GWT基本ウィジェットはこの方法で作成されます。 それでも、カスタムウィジェットを作成する非常に複雑な方法であり、慎重に使用する必要があります。
  • * JavaScriptを使用し、JSNIを使用してウィジェットにラップします*-これは通常、最後の手段としてのみ行う必要があります。 ネイティブメソッドのクロスブラウザーの影響を考慮すると、非常に複雑になり、デバッグも難しくなります。

複合クラスでカスタムウィジェットを作成する

この例では、GWTでのカスタムウィジェットの作成を示す簡単な手順を紹介します。 次の手順に従って、_GWT-基本ウィジェット_の章で作成したGWTアプリケーションを更新します-

ここでは、Compositeクラスを拡張してカスタムウィジェットを作成します。これは、カスタムウィジェットを構築する最も簡単な方法です。

Step Description
1 Create a project with a name HelloWorld under a package com.finddevguides as explained in the GWT - Create Application chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorldl and HelloWorld.java as explained below. Keep rest of the files unchanged.
3 Compile and run the application to verify the result of the implemented logic.

以下は、変更されたモジュール記述子 src/com.finddevguides/HelloWorld.gwt.xml の内容です。

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to = 'helloworld'>
   <!-- Inherit the core Web Toolkit stuff.                        -->
   <inherits name = 'com.google.gwt.user.User'/>

   <!-- Inherit the default GWT style sheet.                       -->
   <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>

   <!-- Specify the app entry point class.                         -->
   <entry-point class = 'com.finddevguides.client.HelloWorld'/>

   <!-- Specify the paths for translatable code                    -->
   <source path = 'client'/>
   <source path = 'shared'/>

</module>

以下は、変更されたスタイルシートファイル war/HelloWorld.css の内容です。

body {
   text-align: center;
   font-family: verdana, sans-serif;
}

h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-align: center;
}

以下は、変更されたHTMLホストファイル war/HelloWorldl の内容です。

<html>
   <head>
      <title>Hello World</title>
      <link rel = "stylesheet" href = "HelloWorld.css"/>
      <script language = "javascript" src = "helloworld/helloworld.nocache.js">
      </script>
   </head>

   <body>
      <h1>Custom Widget Demonstration</h1>
      <div id = "gwtContainer"></div>
   </body>
</html>

カスタムウィジェットの作成を示すJavaファイル src/com.finddevguides/HelloWorld.java の内容を以下に示します。

package com.finddevguides.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;

public class HelloWorld implements EntryPoint {

  /**
 *A composite of a TextBox and a CheckBox that optionally enables it.
   */
   private static class OptionalTextBox extends Composite implements
   ClickHandler {

      private TextBox textBox = new TextBox();
      private CheckBox checkBox = new CheckBox();
      private boolean enabled = true;

      public boolean isEnabled() {
         return enabled;
      }

      public void setEnabled(boolean enabled) {
         this.enabled = enabled;
      }

     /**
 *Style this widget using .optionalTextWidget CSS class.<br/>
      * Style textbox using .optionalTextBox CSS class.<br/>
 *Style checkbox using .optionalCheckBox CSS class.<br/>
      * Constructs an OptionalTextBox with the given caption
 *on the check.
      * @param caption the caption to be displayed with the check box
       */
      public OptionalTextBox(String caption) {
        //place the check above the text box using a vertical panel.
         HorizontalPanel panel = new HorizontalPanel();
        //panel.setBorderWidth(1);
         panel.setSpacing(10);
         panel.add(checkBox);
         panel.add(textBox);

        //all composites must call initWidget() in their constructors.
         initWidget(panel);

        //set style name for entire widget
         setStyleName("optionalTextWidget");

        //set style name for text box
         textBox.setStyleName("optionalTextBox");

        //set style name for check box
         checkBox.setStyleName("optionalCheckBox");
         textBox.setWidth("200");

        //Set the check box's caption, and check it by default.
         checkBox.setText(caption);
         checkBox.setValue(enabled);
         checkBox.addClickHandler(this);
         enableTextBox(enabled,checkBox.getValue());
      }

      public void onClick(ClickEvent event) {
         if (event.getSource() == checkBox) {
           //When the check box is clicked,
           //update the text box's enabled state.
            enableTextBox(enabled,checkBox.getValue());
         }
      }

      private void enableTextBox(boolean enable,boolean isChecked){
         enable = (enable && isChecked) || (!enable && !isChecked);
         textBox.setStyleDependentName("disabled", !enable);
         textBox.setEnabled(enable);
      }
   }

   public void onModuleLoad() {
     //Create an optional text box and add it to the root panel.
      OptionalTextBox otb = new OptionalTextBox(
         "Want to explain the solution?");
      otb.setEnabled(true);
      RootPanel.get().add(otb);
   }
}

すべての変更が完了したら、link:/gwt/gwt_create_application [GWT-アプリケーションの作成]の章で行ったように、アプリケーションをコンパイルして開発モードで実行します。 すべてがあなたのアプリケーションでうまくいけば、これは次の結果を生成します-

GWTカスタムウィジェット

次の点に注意してください

  • Compositeウィジェットを拡張してカスタムウィジェットを作成するのは非常に簡単です。
  • GWT組み込みウィジェット、TextBox、およびCheckBoxを使用してウィジェットを作成し、再利用性の概念を使用しました。
  • TextBoxは、チェックボックスの状態に応じて無効/有効になります。 コントロールを有効/無効にするAPIを提供しました。
  • 文書化されたCSSスタイルを介して内部ウィジェットスタイルを公開しました。

GWT-UiBinder

前書き

UiBinderは、機能とユーザーインターフェイスのビューを分離するように設計されたフレームワークです。

  • UiBinderフレームワークを使用すると、開発者はgwtアプリケーションをHTMLページとして構築し、GWTウィジェットが全体にわたって構成されます。
  • UiBinderフレームワークは、JavaソースコードよりもXML、HTML、CSSに慣れているUIデザイナーとのコラボレーションを容易にします
  • UIBinderは、ユーザーインターフェイスを定義する宣言的な方法を提供します。
  • UIBinderは、プログラムロジックをUIから分離します。
  • UIBinderは、サーブレットに対するJSPと似ています。

UiBinderワークフロー

手順1-UI宣言XMLファイルの作成

XML/HTMLベースのユーザーインターフェイス宣言ファイルを作成します。 この例では、 Login.ui.xml ファイルを作成しました。

<ui:UiBinder xmlns:ui = 'urn:ui:com.google.gwt.uibinder'
   xmlns:gwt = 'urn:import:com.google.gwt.user.client.ui'
   xmlns:res = 'urn:with:com.finddevguides.client.LoginResources'>
   <ui:with type = "com.finddevguides.client.LoginResources" field = "res">
   </ui:with>
   <gwt:HTMLPanel>
   ...
   </gwt:HTMLPanel>
</ui:UiBinder>

ステップ2-後でバインドするためにui:fieldを使用する

XML/HTML要素のui:field属性を使用して、後でバインドするために、XMLのUIフィールドをJAVAファイルのUIフィールドに関連付けます。

<gwt:Label ui:field = "completionLabel1"/>
<gwt:Label ui:field = "completionLabel2"/>

ステップ3-UI XMLに対応するJavaを作成する

Compositeウィジェットを拡張して、JavaベースのXMLベースのレイアウトを作成します。 この例では Login.java ファイルを作成しました。

package com.finddevguides.client;
   ...
public class Login extends Composite {
   ...
}

ステップ4-UiFieldアノテーションでJava UIフィールドをバインドする

*Login.java* で@UiFieldアノテーションを使用して、 *Login.ui.xml* のXMLベースのフィールドにバインドする対応するクラスメンバーを指定します。
public class Login extends Composite {
   ...
   @UiField
   Label completionLabel1;

   @UiField
   Label completionLabel2;
   ...
}

ステップ5-UiTemplateアノテーションを使用してUI XMLとJava UIをバインドする

@UiTemplateアノテーションを使用して、Javaベースのコンポーネント Login.java およびXMLベースのレイアウト Login.ui.xml をバインドするようにGWTに指示します。

public class Login extends Composite {

   private static LoginUiBinder uiBinder = GWT.create(LoginUiBinder.class);

  /*
 *@UiTemplate is not mandatory but allows multiple XML templates
   * to be used for the same widget.
 *Default file loaded will be <class-name>.ui.xml
   */

   @UiTemplate("Login.ui.xml")
   interface LoginUiBinder extends UiBinder<Widget, Login> {
   }
   ...
}

ステップ6-CSSファイルを作成する

外部CSSファイル* Login.css お​​よびcssスタイルに相当するJavaベースのリソース *LoginResources.java ファイルを作成します

.blackText {
   font-family: Arial, Sans-serif;
   color: #000000;
   font-size: 11px;
   text-align: left;
}
...

ステップ7-CSSファイル用のJavaベースのリソースファイルを作成する

package com.finddevguides.client;
...
public interface LoginResources extends ClientBundle {
   public interface MyCss extends CssResource {
      String blackText();

      ...
   }

   @Source("Login.css")
   MyCss style();
}

手順8-Java UIコードファイルでCSSリソースを添付します。

Javaベースのウィジェットクラス Login.java のContructorを使用して、外部CSSファイル* Login.css *を添付します。

public Login() {
   this.res = GWT.create(LoginResources.class);
   res.style().ensureInjected();
   initWidget(uiBinder.createAndBindUi(this));
}

UIBinderの完全な例

この例では、GWTでUIBinderの使用方法を示す簡単な手順を紹介します。 次の手順に従って、_GWTで作成したGWTアプリケーションを更新します-アプリケーションの作成_の章-

Step Description
1 Create a project with a name HelloWorld under a package com.finddevguides as explained in the GWT - Create Application chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorldl and HelloWorld.java as explained below. Keep rest of the files unchanged.
3 Compile and run the application to verify the result of the implemented logic.

以下は、変更されたモジュール記述子 src/com.finddevguides/HelloWorld.gwt.xml の内容です。

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to = 'helloworld'>
   <!-- Inherit the core Web Toolkit stuff.                        -->
   <inherits name = 'com.google.gwt.user.User'/>

   <!-- Inherit the default GWT style sheet.                       -->
   <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>
   <!-- Inherit the UiBinder module.                               -->
   <inherits name = "com.google.gwt.uibinder.UiBinder"/>
   <!-- Specify the app entry point class.                         -->
   <entry-point class = 'com.finddevguides.client.HelloWorld'/>

   <!-- Specify the paths for translatable code                    -->
   <source path ='client'/>
   <source path = 'shared'/>

</module>

以下は、変更されたスタイルシートファイル war/HelloWorld.css の内容です。

body {
   text-align: center;
   font-family: verdana, sans-serif;
}

h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-align: center;
}

以下は、変更されたHTMLホストファイル war/HelloWorldl の内容です。

<html>
   <head>
      <title>Hello World</title>
      <link rel = "stylesheet" href = "HelloWorld.css"/>
      <script language = "javascript" src = "helloworld/helloworld.nocache.js">
      </script>
   </head>

   <body>
      <h1>UiBinder Demonstration</h1>
      <div id = "gwtContainer"></div>
   </body>
</html>

次に、新しいUiBinderテンプレートと所有者クラスを作成します(ファイル→新規→UiBinder)。

GWT UiBinder Wizardステップ1

プロジェクトのクライアントパッケージを選択して、Loginという名前を付けます。 他のすべてのデフォルトのままにします。 [完了]ボタンをクリックすると、プラグインは新しいUiBinderテンプレートと所有者クラスを作成します。

GWT UiBinder Wizard Step 2

*src/com.finddevguides/client* パッケージにLogin.cssファイルを作成し、次のコンテンツをその中に配置します
.blackText {
   font-family: Arial, Sans-serif;
   color: #000000;
   font-size: 11px;
   text-align: left;
}

.redText {
   font-family: Arial, Sans-serif;
   color: #ff0000;
   font-size: 11px;
   text-align: left;
}

.loginButton {
   border: 1px solid #3399DD;
   color: #FFFFFF;
   background: #555555;
   font-size: 11px;
   font-weight: bold;
   margin: 0 5px 0 0;
   padding: 4px 10px 5px;
   text-shadow: 0 -1px 0 #3399DD;
}

.box {
   border: 1px solid #AACCEE;
   display: block;
   font-size: 12px;
   margin: 0 0 5px;
   padding: 3px;
   width: 203px;
}

.background {
   background-color: #999999;
   border: 1px none transparent;
   color: #000000;
   font-size: 11px;
   margin-left: -8px;
   margin-top: 5px;
   padding: 6px;
}
*src/com.finddevguides/client* パッケージにLoginResources.javaファイルを作成し、次のコンテンツをその中に配置します
package com.finddevguides.client;

import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;

public interface LoginResources extends ClientBundle {
  /**
 *Sample CssResource.
   */
   public interface MyCss extends CssResource {
      String blackText();

      String redText();

      String loginButton();

      String box();

      String background();
   }

   @Source("Login.css")
   MyCss style();
}
*src/com.finddevguides/client* パッケージのLogin.ui.xmlの内容を以下で置き換えます
<ui:UiBinder xmlns:ui = 'urn:ui:com.google.gwt.uibinder'
   xmlns:gwt = 'urn:import:com.google.gwt.user.client.ui'
   xmlns:res = 'urn:with:com.finddevguides.client.LoginResources'>

   <ui:with type = "com.finddevguides.client.LoginResources" field = "res">
   </ui:with>

   <gwt:HTMLPanel>
      <div align = "center">

         <gwt:VerticalPanel res:styleName = "style.background">
            <gwt:Label text = "Login" res:styleName = "style.blackText"/>
            <gwt:TextBox ui:field="loginBox" res:styleName = "style.box"/>
            <gwt:Label text = "Password" res:styleName = "style.blackText"/>
            <gwt:PasswordTextBox ui:field = "passwordBox" res:styleName = "style.box"/>

            <gwt:HorizontalPanel verticalAlignment = "middle">
               <gwt:Button ui:field = "buttonSubmit" text="Submit"
                  res:styleName = "style.loginButton"/>
               <gwt:CheckBox ui:field = "myCheckBox"/>
               <gwt:Label ui:field = "myLabel" text = "Remember me"
                  res:styleName = "style.blackText"/>
            </gwt:HorizontalPanel>

            <gwt:Label ui:field = "completionLabel1" res:styleName = "style.blackText"/>
            <gwt:Label ui:field = "completionLabel2" res:styleName = "style.blackText"/>
         </gwt:VerticalPanel>

      </div>
   </gwt:HTMLPanel>

</ui:UiBinder>
*src/com.finddevguides/client* パッケージのLogin.javaの内容を次のように置き換えます
package com.finddevguides.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class Login extends Composite {

   private static LoginUiBinder uiBinder = GWT.create(LoginUiBinder.class);

  /*
 *@UiTemplate is not mandatory but allows multiple XML templates
   * to be used for the same widget.
 *Default file loaded will be <class-name>.ui.xml
   */
   @UiTemplate("Login.ui.xml")
   interface LoginUiBinder extends UiBinder<Widget, Login> {
   }

   @UiField(provided = true)
   final LoginResources res;

   public Login() {
      this.res = GWT.create(LoginResources.class);
      res.style().ensureInjected();
      initWidget(uiBinder.createAndBindUi(this));
   }

   @UiField
   TextBox loginBox;

   @UiField
   TextBox passwordBox;

   @UiField
   Label completionLabel1;

   @UiField
   Label completionLabel2;

   private Boolean tooShort = false;

  /*
 *Method name is not relevant, the binding is done according to the class
   * of the parameter.
    */
   @UiHandler("buttonSubmit")
   void doClickSubmit(ClickEvent event) {
      if (!tooShort) {
         Window.alert("Login Successful!");
      } else {
         Window.alert("Login or Password is too short!");
      }
   }

   @UiHandler("loginBox")
   void handleLoginChange(ValueChangeEvent<String> event) {
      if (event.getValue().length() < 6) {
         completionLabel1.setText("Login too short (Size must be > 6)");
         tooShort = true;
      } else {
         tooShort = false;
         completionLabel1.setText("");
      }
   }

   @UiHandler("passwordBox")
   void handlePasswordChange(ValueChangeEvent<String> event) {
      if (event.getValue().length() < 6) {
         tooShort = true;
         completionLabel2.setText("Password too short (Size must be > 6)");
      } else {
         tooShort = false;
         completionLabel2.setText("");
      }
   }
}

UiBinderの使用方法を示すJavaファイル src/com.finddevguides/HelloWorld.java の内容を見てみましょう。

package com.finddevguides.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.RootPanel;

public class HelloWorld implements EntryPoint {
   public void onModuleLoad() {
      RootPanel.get().add(new Login());
   }
}

すべての変更が完了したら、link:/gwt/gwt_create_application [GWT-アプリケーションの作成]の章で行ったように、アプリケーションをコンパイルして開発モードで実行します。 すべてがあなたのアプリケーションでうまくいけば、これは次の結果を生成します-

GWT UiBinderデモ

GWT-RPC通信

GWTベースのアプリケーションは通常、クライアント側モジュールとサーバー側モジュールで構成されます。 クライアント側のコードはブラウザーで実行され、サーバー側のコードはWebサーバーで実行されます。 クライアント側のコードは、サーバー側のデータにアクセスするために、ネットワークを介してHTTP要求を作成する必要があります。

RPC、リモートプロシージャコールは、クライアントコードがサーバー側のメソッドを直接実行できるGWTで使用されるメカニズムです。

  • GWT RPCはサーブレットベースです。
  • GWT RPCは非同期であり、通信中にクライアントがブロックされることはありません。
  • GWT RPC Javaオブジェクトを使用すると、クライアントとサーバー間で直接送信できます(GWTフレームワークによって自動的にシリアル化されます)。
  • サーバー側サーブレットは service と呼ばれます。
  • クライアント側コードからサーバー側サーブレットのメソッドを呼び出すリモートプロシージャコールは、*サービスの呼び出し*と呼ばれます。

GWT RPCコンポーネント

以下は、GWT RPC通信メカニズムで使用される3つのコンポーネントです。

  • サーバーで実行されるリモートサービス(サーバー側サーブレット)。
  • そのサービスを呼び出すクライアントコード。
  • クライアントとサーバー間で渡されるJavaデータオブジェクト。

GWTクライアントとサーバーは、データを自動的にシリアル化および逆シリアル化するため、開発者はオブジェクトをシリアル化/逆シリアル化する必要がなく、データオブジェクトはHTTPを介して移動できます。

次の図は、RPCアーキテクチャを示しています。

GWT RPCワークフロー

RPCの使用を開始するには、GWTの規則に従う必要があります。

RPC通信ワークフロー

手順1-シリアル化可能なモデルクラスを作成する

クライアント側で、直列化可能なJavaモデルオブジェクトを定義します。

public class Message implements Serializable {
   ...
   private String message;
   public Message(){};

   public void setMessage(String message) {
      this.message = message;
   }
   ...
}

ステップ2-サービスインターフェイスの作成

すべてのサービスメソッドをリストするRemoteServiceを拡張するクライアント側のサービスのインターフェイスを定義します。

アノテーション@RemoteServiceRelativePathを使用して、サービスをモジュールベースURLに関連するリモートサーブレットのデフォルトパスにマップします。

@RemoteServiceRelativePath("message")
public interface MessageService extends RemoteService {
   Message getMessage(String input);
}

手順3-非同期サービスインターフェイスを作成する

GWTクライアントコードで使用されるクライアント側(上記のサービスと同じ場所)でサービスする非同期インターフェイスを定義します。

public interface MessageServiceAsync {
   void getMessage(String input, AsyncCallback<Message> callback);
}

ステップ4-サービス実装サーブレットクラスを作成する

サーバー側でインターフェースを実装すると、そのクラスはRemoteServiceServletクラスを拡張する必要があります。

public class MessageServiceImpl extends RemoteServiceServlet
   implements MessageService{
   ...
   public Message getMessage(String input) {
      String messageString = "Hello " + input + "!";
      Message message = new Message();
      message.setMessage(messageString);
      return message;
   }
}

手順5-Web.xmlを更新してサーブレット宣言を含める

Webアプリケーションデプロイメント記述子(web.xml)を編集して、MessageServiceImplサーブレット宣言を含めます。

<web-app>
   ...
   <servlet>
      <servlet-name>messageServiceImpl</servlet-name>
      <servlet-class>com.finddevguides.server.MessageServiceImpl
      </servlet-class>
   </servlet>

   <servlet-mapping>
      <servlet-name>messageServiceImpl</servlet-name>
      <url-pattern>/helloworld/message</url-pattern>
   </servlet-mapping>
</web-app>

手順6-アプリケーションコードでリモートプロシージャコールを行う

サービスプロキシクラスを作成します。

MessageServiceAsync messageService = GWT.create(MessageService.class);

AsyncCallback Handlerを作成して、サーバーがクライアントにメッセージを返すRPCコールバックを処理します

class MessageCallBack implements AsyncCallback<Message> {

   @Override
   public void onFailure(Throwable caught) {
      Window.alert("Unable to obtain server response: "
      + caught.getMessage());
   }

   @Override
   public void onSuccess(Message result) {
      Window.alert(result.getMessage());
   }
}

ユーザーがUIと対話するときにリモートサービスを呼び出す

public class HelloWorld implements EntryPoint {
   ...
   public void onModuleLoad() {
   ...
      buttonMessage.addClickHandler(new ClickHandler() {
         @Override
         public void onClick(ClickEvent event) {
            messageService.getMessage(txtName.getValue(),
            new MessageCallBack());
         }
      });
   ...
   }
}

RPC通信の完全な例

この例では、簡単な手順でGWTのRPC通信の例を示します。 次の手順に従って、_GWTで作成したGWTアプリケーションを更新します-アプリケーションの作成_の章-

Step Description
1 Create a project with a name HelloWorld under a package com.finddevguides as explained in the GWT - Create Application chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorldl and HelloWorld.java as explained below. Keep rest of the files unchanged.
3 Compile and run the application to verify the result of the implemented logic.

以下は、変更されたモジュール記述子 src/com.finddevguides/HelloWorld.gwt.xml の内容です。

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to = 'helloworld'>
   <!-- Inherit the core Web Toolkit stuff.                        -->
   <inherits name = 'com.google.gwt.user.User'/>

   <!-- Inherit the default GWT style sheet.                       -->
   <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>
   <!-- Inherit the UiBinder module.                               -->
   <inherits name = "com.google.gwt.uibinder.UiBinder"/>
   <!-- Specify the app entry point class.                         -->
   <entry-point class = 'com.finddevguides.client.HelloWorld'/>

   <!-- Specify the paths for translatable code                    -->
   <source path = 'client'/>
   <source path = 'shared'/>

</module>

以下は、変更されたスタイルシートファイル war/HelloWorld.css の内容です。

body {
   text-align: center;
   font-family: verdana, sans-serif;
}

h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-align: center;
}

以下は、変更されたHTMLホストファイル war/HelloWorldl の内容です。

<html>
   <head>
      <title>Hello World</title>
      <link rel = "stylesheet" href = "HelloWorld.css"/>
      <script language = "javascript" src = "helloworld/helloworld.nocache.js">
      </script>
   </head>

   <body>
      <h1>RPC Communication Demonstration</h1>
      <div id = "gwtContainer"></div>
   </body>
</html>
*src/com.finddevguides/client* パッケージにMessage.javaファイルを作成し、次のコンテンツをその中に配置します
package com.finddevguides.client;

import java.io.Serializable;

public class Message implements Serializable {

   private static final long serialVersionUID = 1L;
   private String message;
   public Message(){};

   public void setMessage(String message) {
      this.message = message;
   }

   public String getMessage() {
      return message;
   }
}
*src/com.finddevguides/client* パッケージにMessageService.javaファイルを作成し、次のコンテンツをその中に配置します
package com.finddevguides.client;

import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;

@RemoteServiceRelativePath("message")
public interface MessageService extends RemoteService {
   Message getMessage(String input);
}
*src/com.finddevguides/client* パッケージにMessageServiceAsync.javaファイルを作成し、次のコンテンツをその中に配置します
package com.finddevguides.client;

import com.google.gwt.user.client.rpc.AsyncCallback;

public interface MessageServiceAsync {
   void getMessage(String input, AsyncCallback<Message> callback);
}
*src/com.finddevguides/server* パッケージにMessageServiceImpl.javaファイルを作成し、次のコンテンツをその中に配置します
package com.finddevguides.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.finddevguides.client.Message;
import com.finddevguides.client.MessageService;

public class MessageServiceImpl extends RemoteServiceServlet
   implements MessageService{

   private static final long serialVersionUID = 1L;

   public Message getMessage(String input) {
      String messageString = "Hello " + input + "!";
      Message message = new Message();
      message.setMessage(messageString);
      return message;
   }
}

変更されたWebアプリケーションデプロイメント記述子 war/WEB-INF/web.xml の内容を更新して、MessageServiceImplサーブレット宣言を含めます。

<?xml version = "1.0" encoding = "UTF-8"?>
<!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>
   <!-- Default page to serve -->
   <welcome-file-list>
      <welcome-file>HelloWorldl</welcome-file>
   </welcome-file-list>

   <servlet>
      <servlet-name>messageServiceImpl</servlet-name>
      <servlet-class>com.finddevguides.server.MessageServiceImpl
      </servlet-class>
   </servlet>

   <servlet-mapping>
      <servlet-name>messageServiceImpl</servlet-name>
      <url-pattern>/helloworld/message</url-pattern>
   </servlet-mapping>
</web-app>
*src/com.finddevguides/client* パッケージのHelloWorld.javaの内容を次のように置き換えます
package com.finddevguides.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class HelloWorld implements EntryPoint {

   private MessageServiceAsync messageService =
   GWT.create(MessageService.class);

   private class MessageCallBack implements AsyncCallback<Message> {
      @Override
      public void onFailure(Throwable caught) {
        /*server side error occured*/
         Window.alert("Unable to obtain server response: " + caught.getMessage());
      }
      @Override
      public void onSuccess(Message result) {
         /*server returned result, show user the message*/
         Window.alert(result.getMessage());
      }
   }

   public void onModuleLoad() {
     /*create UI */
      final TextBox txtName = new TextBox();
      txtName.setWidth("200");
      txtName.addKeyUpHandler(new KeyUpHandler() {
         @Override
         public void onKeyUp(KeyUpEvent event) {
            if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER){
              /*make remote call to server to get the message*/
               messageService.getMessage(txtName.getValue(),
               new MessageCallBack());
            }
         }
      });
      Label lblName = new Label("Enter your name: ");

      Button buttonMessage = new Button("Click Me!");

      buttonMessage.addClickHandler(new ClickHandler() {
         @Override
         public void onClick(ClickEvent event) {
           /*make remote call to server to get the message*/
            messageService.getMessage(txtName.getValue(),
            new MessageCallBack());
         }
      });

      HorizontalPanel hPanel = new HorizontalPanel();
      hPanel.add(lblName);
      hPanel.add(txtName);
      hPanel.setCellWidth(lblName, "130");

      VerticalPanel vPanel = new VerticalPanel();
      vPanel.setSpacing(10);
      vPanel.add(hPanel);
      vPanel.add(buttonMessage);
      vPanel.setCellHorizontalAlignment(buttonMessage,
      HasHorizontalAlignment.ALIGN_RIGHT);

      DecoratorPanel panel = new DecoratorPanel();
      panel.add(vPanel);

     //Add widgets to the root panel.
      RootPanel.get("gwtContainer").add(panel);
   }
}

すべての変更が完了したら、link:/gwt/gwt_create_application [GWT-アプリケーションの作成]の章で行ったように、アプリケーションをコンパイルして開発モードで実行します。 すべてがあなたのアプリケーションでうまくいけば、これは次の結果を生成します-

GWT RPC Demo

GWT-JUnit統合

GWTは、JUnitテストフレームワークを使用したクライアント側コードの自動テストの優れたサポートを提供します。 この記事では、GWTとJUNITの統合について説明します。

Junitアーカイブをダウンロードする

JUnit公式サイト-https://www.junit.org/[https://www.junit.org]

ダウンロード Junit-4.10.jar

OS Archive name
Windows junit4.10.jar
Linux junit4.10.jar
Mac junit4.10.jar

ダウンロードしたjarファイルをコンピューター上のある場所に保管します。 C:/> JUNIT に保存しました

GWTインストールフォルダーを見つける

OS GWT installation folder
Windows C:\GWT\gwt-2.1.0
Linux /usr/local/GWT/gwt-2.1.0
Mac /Library/GWT/gwt-2.1.0

GWTTestCaseクラス

GWTは、JUnit統合を提供する GWTTestCase 基本クラスを提供します。 JUnitでGWTTestCaseを拡張するコンパイル済みクラスを実行すると、テスト実行中のアプリケーションの動作をエミュレートするHtmlUnitブラウザーが起動します。

GWTTestCaseはJUnitのTestCaseから派生したクラスであり、JUnit TestRunnerを使用して実行できます。

webAppCreatorを使用する

GWTは、スターターテストケースを生成できる特別なコマンドラインツール webAppCreator に加えて、開発モードと本番モードの両方でテストするためのantターゲットとEclipse起動構成を提供します。

コマンドプロンプトを開き、 C:\> GWT_WORKSPACE> に移動して、テストサポート付きの新しいプロジェクトを作成します。次のコマンドを実行します。

C:\GWT_WORKSPACE>C:\GWT\gwt-2.1.0\webAppCreator
   -out HelloWorld
   -junit C:\JUNIT\junit-4.10.jar
   com.finddevguides.HelloWorld

注目すべきポイント

  • webAppCreatorコマンドラインユーティリティを実行しています。
  • HelloWorldは、作成するプロジェクトの名前です
  • -junitオプションはwebAppCreatorにjunitサポートをプロジェクトに追加するよう指示します
  • com.finddevguides.HelloWorldはモジュールの名前です

出力を確認します。

Created directory HelloWorld\src
Created directory HelloWorld\war
Created directory HelloWorld\war\WEB-INF
Created directory HelloWorld\war\WEB-INF\lib
Created directory HelloWorld\src\com\finddevguides
Created directory HelloWorld\src\com\finddevguides\client
Created directory HelloWorld\src\com\finddevguides\server
Created directory HelloWorld\src\com\finddevguides\shared
Created directory HelloWorld\test\com\finddevguides
Created directory HelloWorld\test\com\finddevguides\client
Created file HelloWorld\src\com\finddevguides\HelloWorld.gwt.xml
Created file HelloWorld\war\HelloWorldl
Created file HelloWorld\war\HelloWorld.css
Created file HelloWorld\war\WEB-INF\web.xml
Created file HelloWorld\src\com\finddevguides\client\HelloWorld.java
Created file
HelloWorld\src\com\finddevguides\client\GreetingService.java
Created file
HelloWorld\src\com\finddevguides\client\GreetingServiceAsync.java
Created file
HelloWorld\src\com\finddevguides\server\GreetingServiceImpl.java
Created file HelloWorld\src\com\finddevguides\shared\FieldVerifier.java
Created file HelloWorld\build.xml
Created file HelloWorld\README.txt
Created file HelloWorld\test\com\finddevguides\HelloWorldJUnit.gwt.xml
Created file HelloWorld\test\com\finddevguides\client\HelloWorldTest.java
Created file HelloWorld\.project
Created file HelloWorld\.classpath
Created file HelloWorld\HelloWorld.launch
Created file HelloWorld\HelloWorldTest-dev.launch
Created file HelloWorld\HelloWorldTest-prod.launch

テストクラスの理解:HelloWorldTest.java

package com.finddevguides.client;

import com.finddevguides.shared.FieldVerifier;
import com.google.gwt.core.client.GWT;
import com.google.gwt.junit.client.GWTTestCase;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;

/**
 *GWT JUnit tests must extend GWTTestCase.
*/
public class HelloWorldTest extends GWTTestCase {

  /**
 *must refer to a valid module that sources this class.
   */
   public String getModuleName() {
      return "com.finddevguides.HelloWorldJUnit";
   }

  /**
 *tests the FieldVerifier.
   */
   public void testFieldVerifier() {
      assertFalse(FieldVerifier.isValidName(null));
      assertFalse(FieldVerifier.isValidName(""));
      assertFalse(FieldVerifier.isValidName("a"));
      assertFalse(FieldVerifier.isValidName("ab"));
      assertFalse(FieldVerifier.isValidName("abc"));
      assertTrue(FieldVerifier.isValidName("abcd"));
   }

  /**
 *this test will send a request to the server using the greetServer
   * method in GreetingService and verify the response.
    */
   public void testGreetingService() {
     /*create the service that we will test.*/
      GreetingServiceAsync greetingService =
      GWT.create(GreetingService.class);
      ServiceDefTarget target = (ServiceDefTarget) greetingService;
      target.setServiceEntryPoint(GWT.getModuleBaseURL()
      + "helloworld/greet");

     /*since RPC calls are asynchronous, we will need to wait
       for a response after this test method returns. This line
       tells the test runner to wait up to 10 seconds
       before timing out.*/
      delayTestFinish(10000);

     /*send a request to the server.*/
      greetingService.greetServer("GWT User",
         new AsyncCallback<String>() {
         public void onFailure(Throwable caught) {
           /*The request resulted in an unexpected error.*/
            fail("Request failure: " + caught.getMessage());
         }

         public void onSuccess(String result) {
           /*verify that the response is correct.*/
            assertTrue(result.startsWith("Hello, GWT User!"));

           /* now that we have received a response, we need to
             tell the test runner that the test is complete.
             You must call finishTest() after an asynchronous test
             finishes successfully, or the test will time out.*/
            finishTest();
         }
      });
   }
}

注目すべきポイント

Sr.No. Note
1 HelloWorldTest class was generated in the com.finddevguides.client package under the HelloWorld/test directory.
2 HelloWorldTest class will contain unit test cases for HelloWorld.
3 HelloWorldTest class extends the GWTTestCase class in the com.google.gwt.junit.client package.
4 HelloWorldTest class has an abstract method (getModuleName) that must return the name of the GWT module. For HelloWorld, this is com.finddevguides.HelloWorldJUnit.
5 HelloWorldTest class is generated with two sample test cases testFieldVerifier, testSimple. We’ve added testGreetingService.
6 These methods use one of the many assert* functions that it inherits from the JUnit Assert class, which is an ancestor of GWTTestCase.
7 The assertTrue(boolean) function asserts that the boolean argument passed in evaluates to true. If not, the test will fail when run in JUnit.

GWT-JUnit統合の完全な例

この例では、簡単な手順でGWTでのJUnit統合の例を示します。

上記で作成したGWTアプリケーションを更新するには、次の手順に従います-

Step Description
1 Import the project with a name HelloWorld in eclipse using import existing project wizard (File → Import → General → Existing Projects into workspace).
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorldl and HelloWorld.java as explained below. Keep rest of the files unchanged.
3 Compile and run the application to verify the result of the implemented logic.

以下は、Eclipseのプロジェクト構造です。

プロジェクト構造

以下は、変更されたモジュール記述子 src/com.finddevguides/HelloWorld.gwt.xml の内容です。

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to = 'helloworld'>
   <!-- Inherit the core Web Toolkit stuff.                        -->
   <inherits name = 'com.google.gwt.user.User'/>

   <!-- Inherit the default GWT style sheet.                       -->
   <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>
   <!-- Inherit the UiBinder module.                               -->
   <inherits name = "com.google.gwt.uibinder.UiBinder"/>
   <!-- Specify the app entry point class.                         -->
   <entry-point class = 'com.finddevguides.client.HelloWorld'/>

   <!-- Specify the paths for translatable code                    -->
   <source path = 'client'/>
   <source path = 'shared'/>

</module>

以下は、変更されたスタイルシートファイル war/HelloWorld.css の内容です。

body {
   text-align: center;
   font-family: verdana, sans-serif;
}

h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-align: center;
}

以下は、変更されたHTMLホストファイル war/HelloWorldl の内容です。

<html>
   <head>
      <title>Hello World</title>
      <link rel = "stylesheet" href = "HelloWorld.css"/>
      <script language = "javascript" src = "helloworld/helloworld.nocache.js">
      </script>
   </head>

   <body>
      <h1>JUnit Integration Demonstration</h1>
      <div id = "gwtContainer"></div>
   </body>
</html>
*src/com.finddevguides/client* パッケージのHelloWorld.javaの内容を次のように置き換えます
package com.finddevguides.client;

import com.google.gwt.core.client.EntryPoint;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class HelloWorld implements EntryPoint {

   public void onModuleLoad() {
     /*create UI */
      final TextBox txtName = new TextBox();
      txtName.setWidth("200");
      txtName.addKeyUpHandler(new KeyUpHandler() {
         @Override
         public void onKeyUp(KeyUpEvent event) {
            if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER){
               Window.alert(getGreeting(txtName.getValue()));
            }
         }
      });
      Label lblName = new Label("Enter your name: ");

      Button buttonMessage = new Button("Click Me!");

      buttonMessage.addClickHandler(new ClickHandler() {
         @Override
         public void onClick(ClickEvent event) {
            Window.alert(getGreeting(txtName.getValue()));
         }
      });

      HorizontalPanel hPanel = new HorizontalPanel();
      hPanel.add(lblName);
      hPanel.add(txtName);
      hPanel.setCellWidth(lblName, "130");

      VerticalPanel vPanel = new VerticalPanel();
      vPanel.setSpacing(10);
      vPanel.add(hPanel);
      vPanel.add(buttonMessage);
      vPanel.setCellHorizontalAlignment(buttonMessage,
      HasHorizontalAlignment.ALIGN_RIGHT);

      DecoratorPanel panel = new DecoratorPanel();
      panel.add(vPanel);

     //Add widgets to the root panel.
      RootPanel.get("gwtContainer").add(panel);
   }

   public String getGreeting(String name){
      return "Hello "+name+"!";
   }
}
*test/com.finddevguides/client* パッケージのHelloWorldTest.javaの内容を以下で置き換えます
package com.finddevguides.client;

import com.finddevguides.shared.FieldVerifier;
import com.google.gwt.core.client.GWT;
import com.google.gwt.junit.client.GWTTestCase;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;

/**
 *GWT JUnit tests must extend GWTTestCase.
*/
public class HelloWorldTest extends GWTTestCase {

  /**
 *must refer to a valid module that sources this class.
   */
   public String getModuleName() {
      return "com.finddevguides.HelloWorldJUnit";
   }

  /**
 *tests the FieldVerifier.
   */
   public void testFieldVerifier() {
      assertFalse(FieldVerifier.isValidName(null));
      assertFalse(FieldVerifier.isValidName(""));
      assertFalse(FieldVerifier.isValidName("a"));
      assertFalse(FieldVerifier.isValidName("ab"));
      assertFalse(FieldVerifier.isValidName("abc"));
      assertTrue(FieldVerifier.isValidName("abcd"));
   }

  /**
 *this test will send a request to the server using the greetServer
     * method in GreetingService and verify the response.
   */
   public void testGreetingService() {
     /*create the service that we will test.*/
      GreetingServiceAsync greetingService =
      GWT.create(GreetingService.class);
      ServiceDefTarget target = (ServiceDefTarget) greetingService;
      target.setServiceEntryPoint(GWT.getModuleBaseURL()
      + "helloworld/greet");

     /*since RPC calls are asynchronous, we will need to wait
       for a response after this test method returns. This line
       tells the test runner to wait up to 10 seconds
       before timing out.*/
      delayTestFinish(10000);

     /*send a request to the server.*/
      greetingService.greetServer("GWT User",
         new AsyncCallback<String>() {
         public void onFailure(Throwable caught) {
           /*The request resulted in an unexpected error.*/
            fail("Request failure: " + caught.getMessage());
         }

         public void onSuccess(String result) {
           /*verify that the response is correct.*/
            assertTrue(result.startsWith("Hello, GWT User!"));

           /* now that we have received a response, we need to
             tell the test runner that the test is complete.
             You must call finishTest() after an asynchronous test
             finishes successfully, or the test will time out.*/
            finishTest();
         }
      });

     /**
 *tests the getGreeting method.
     */
      public void testGetGreeting() {
         HelloWorld helloWorld = new HelloWorld();
         String name = "Robert";
         String expectedGreeting = "Hello "+name+"!";
         assertEquals(expectedGreeting,helloWorld.getGreeting(name));
      }
   }
}

生成された起動構成を使用してEclipseでテストケースを実行する

開発モードと本番モードの両方でwebAppCreatorによって生成された起動構成を使用して、Eclipseで単体テストを実行します。

開発モードでJUnitテストを実行する

  • Eclipseメニューバーから、[実行]→[実行構成…​]を選択します。
  • JUnitセクションで、HelloWorldTest-devを選択します
  • 引数への変更を保存するには、適用を押します
  • テストを実行するには、実行を押します

すべてがあなたのアプリケーションでうまくいけば、これは次の結果を生成します-

GWT Junit結果

実稼働モードでJUnitテストを実行する

  • Eclipseメニューバーから、[実行]→[実行構成…​]を選択します。
  • JUnitセクションで、HelloWorldTest-prodを選択します
  • 引数への変更を保存するには、適用を押します
  • テストを実行するには、実行を押します

すべてがあなたのアプリケーションでうまくいけば、これは次の結果を生成します-

GWT Junit結果

GWT-アプリケーションのデバッグ

GWTは、クライアント側とサーバー側のコードをデバッグする優れた機能を提供します。

開発モードでは、GWTアプリケーションはJavaコードベースであり、JavaScriptに変換されません。

アプリケーションが開発モードで実行されている場合、Java仮想マシン(JVM)は実際にアプリケーションコードをコンパイル済みJavaバイトコードとして実行し、GWT機能を使用してブラウザーウィンドウに接続します。

GWTはブラウザーベースのプラグインを使用してJVMに接続します。

そのため、開発者はJavaベースのIDEを自由に使用して、クライアント側のGWTコードとサーバー側のコードの両方をデバッグできます。

この記事では、Eclipseを使用したGWTクライアントコードのデバッグの使用方法を示します。 私たちは次のタスクを行います-

  • コードにブレークポイントを設定し、BreakPoint Explorerで確認します。
  • デバッグ中にコードを1行ずつステップ実行します。
  • 変数の値を表示します。
  • すべての変数の値を調べます。
  • 式の値を調べます。
  • 中断されたスレッドのスタックフレームを表示します。

デバッグの例

この例では、GWTアプリケーションのデバッグを示す簡単な手順を紹介します。 次の手順に従って、_GWTで作成したGWTアプリケーションを更新します-アプリケーションの作成_の章-

Step Description
1 Create a project with a name HelloWorld under a package com.finddevguides as explained in the GWT - Create Application chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorldl and HelloWorld.java as explained below. Keep rest of the files unchanged.
3 Compile and run the application to verify the result of the implemented logic.

以下は、変更されたモジュール記述子 src/com.finddevguides/HelloWorld.gwt.xml の内容です。

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to = 'helloworld'>
   <!-- Inherit the core Web Toolkit stuff.                        -->
   <inherits name = 'com.google.gwt.user.User'/>

   <!-- Inherit the default GWT style sheet.                       -->
   <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>

   <!-- Specify the app entry point class.                         -->
   <entry-point class = 'com.finddevguides.client.HelloWorld'/>

   <!-- Specify the paths for translatable code                    -->
   <source path = 'client'/>
   <source path = 'shared'/>

</module>

以下は、変更されたスタイルシートファイル war/HelloWorld.css の内容です。

body {
   text-align: center;
   font-family: verdana, sans-serif;
}

h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-align: center;
}

.gwt-Label{
   font-size: 150%;
   font-weight: bold;
   color:red;
   padding:5px;
   margin:5px;
}

以下は、2つのボタンに対応するように変更されたHTMLホストファイル war/HelloWorldl の内容です。

<html>
   <head>
      <title>Hello World</title>
      <link rel = "stylesheet" href = "HelloWorld.css"/>
      <script language = "javascript" src = "helloworld/helloworld.nocache.js">
      </script>
   </head>

   <body>
      <h1>Debugging Application Demonstration</h1>
      <div id = "gwtContainer"></div>
   </body>
</html>

Javaファイル src/com.finddevguides/HelloWorld.java の以下のコンテンツを使用して、GWTコードのデバッグ機能を示します。

package com.finddevguides.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class HelloWorld implements EntryPoint {

   public void onModuleLoad() {
     /*create UI */
      final TextBox txtName = new TextBox();
      txtName.setWidth("200");
      txtName.addKeyUpHandler(new KeyUpHandler() {
         @Override
         public void onKeyUp(KeyUpEvent event) {
            if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER){
               Window.alert(getGreeting(txtName.getValue()));
            }
         }
      });
      Label lblName = new Label("Enter your name: ");

      Button buttonMessage = new Button("Click Me!");

      buttonMessage.addClickHandler(new ClickHandler() {
      @Override
      public void onClick(ClickEvent event) {
         Window.alert(getGreeting(txtName.getValue()));
      }});

      HorizontalPanel hPanel = new HorizontalPanel();
      hPanel.add(lblName);
      hPanel.add(txtName);
      hPanel.setCellWidth(lblName, "130");

      VerticalPanel vPanel = new VerticalPanel();
      vPanel.setSpacing(10);
      vPanel.add(hPanel);
      vPanel.add(buttonMessage);
      vPanel.setCellHorizontalAlignment(buttonMessage,
      HasHorizontalAlignment.ALIGN_RIGHT);

      DecoratorPanel panel = new DecoratorPanel();
      panel.add(vPanel);

     //Add widgets to the root panel.
      RootPanel.get("gwtContainer").add(panel);
   }

   public String getGreeting(String name){
      return "Hello "+name+"!";
   }
}

ステップ1-ブレークポイントを配置する

HelloWorld.javaの* onModuleLoad()*の最初の行にブレークポイントを配置します

ブレークポイントの適用GWT

ステップ2-アプリケーションのデバッグ

次に、アプリケーションのデバッグアプリケーションメニューのデバッグをクリックし、 HelloWorld アプリケーションを選択してアプリケーションをデバッグします。

GWTデバッグボタン

すべてが正常な場合、以下に示すURLを含むEclipseでGWT開発モードがアクティブになっている必要があります。 URLをダブルクリックしてGWTアプリケーションを開きます。

GWTデバッグアプリケーション

アプリケーションが起動するとすぐに、エントリポイントメソッドの最初の行にブレークポイントを配置したため、Eclipseブレークポイントにフォーカスが表示されます。

GWTデバッグアプリケーション

中断されたスレッドのスタックトレースを確認できます。

GWTデバッグStacktrace

式の値を確認できます。

GWTデバッグ式

配置されたブレークポイントのリストを見ることができます。

GWTデバッグブレークポイント

onModuleLoad()メソッドの最後の行に到達するまでF6を押し続けます。 ファンクションキーの参照として、F6はコードを1行ずつ検査し、F5はさらに内側に進み、F8はアプリケーションを再開します。 これで、onModuleLoad()メソッドのすべての変数の値のリストを確認できます。

GWTデバッグ変数

GWTクライアントコードは、Javaアプリケーションのデバッグと同じ方法でデバッグできます。 任意の行にブレークポイントを配置し、GWTのデバッグ機能を試してください。

GWT-国際化

GWTはGWTアプリケーションを国際化するための3つの方法を提供します。プロジェクトで最も一般的に使用されている静的文字列国際化の使用方法を示します。

Sr.No. Technique & Description
1

Static String Internationalization

この手法は最も一般的であり、実行時のオーバーヘッドはほとんど必要ありません。は、定数文字列とパラメータ化された文字列の両方を変換するための非常に効率的な手法です。実装が最も簡単です。

静的文字列の国際化では、標準のJavaプロパティファイルを使用して、翻訳された文字列とパラメータ化されたメッセージを格納し、厳密に型指定されたJavaインターフェイスを作成して値を取得します。

2

Dynamic String Internationalization

この手法は非常に柔軟ですが、静的な文字列の国際化よりも時間がかかります。 ホストページにはローカライズされた文字列が含まれているため、新しいロケールを追加するときにアプリケーションを再コンパイルする必要はありません。 GWTアプリケーションを既存のサーバー側ローカリゼーションシステムと統合する場合は、この手法を使用します。

3

Localizable Interface

この手法は、3つの手法の中で最も強力です。 Localizableを実装すると、カスタムタイプのローカライズバージョンを作成できます。 これは高度な国際化手法です。

GWTアプリケーションの国際化のワークフロー

手順1-プロパティファイルを作成する

アプリケーションで使用されるメッセージを含むプロパティファイルを作成します。 この例では、 HelloWorldMessages.properties ファイルを作成しました。

enterName = Enter your name
clickMe = Click Me
applicationTitle = Application Internationalization Demonstration
greeting = Hello {0}

ロケール固有の翻訳された値を含むプロパティファイルを作成します。 この例では、 HelloWorldMessages_de.properties ファイルを作成しました。 このファイルにはドイツ語の翻訳が含まれています。 _deはドイツ語のロケールを指定し、アプリケーションでドイツ語をサポートします。

Eclipseを使用してプロパティファイルを作成している場合は、ファイルのエンコーディングをUTF-8に変更します。ファイルを選択して右クリックし、プロパティウィンドウを開きます。 変更を適用して保存します。

enterName = Geben Sie Ihren Namen
clickMe = Klick mich
applicationTitle = Anwendung Internationalisierung Demonstration
greeting = Hallo {0}

ステップ2-モジュール記述子XMLファイルへのi18nモジュールの追加

モジュールファイル HelloWorld.gwt.xml を更新して、ドイツ語ロケールのサポートを含めます

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to = 'helloworld'>
   ...
   <extend-property name = "locale" values="de"/>
   ...
</module>

手順3-プロパティファイルに相当するインターフェイスを作成する

GWTのメッセージインターフェイスを拡張して、内部化のサポートを含めることにより、HelloWorldMessages.javaインターフェイスを作成します。 プロパティファイルのキーと同じメソッド名を含める必要があります。 プレースホルダーは文字列引数に置き換えられます。

public interface HelloWorldMessages extends Messages {

   @DefaultMessage("Enter your name")
   String enterName();

   @DefaultMessage("Click Me")
   String clickMe();

   @DefaultMessage("Application Internalization Demonstration")
   String applicationTitle();

   @DefaultMessage("Hello {0}")
   String greeting(String name);
}

手順4-UIコンポーネントでメッセージインターフェイスを使用します。

*HelloWorld* の *HelloWorldMessages* のオブジェクトを使用して、メッセージを取得します。
public class HelloWorld implements EntryPoint {

  /*create an object of HelloWorldMessages interface
      using GWT.create() method*/
   private HelloWorldMessages messages =
   GWT.create(HelloWorldMessages.class);

   public void onModuleLoad() {
   ...
      Label titleLabel = new Label(messages.applicationTitle());
     //Add title to the application
      RootPanel.get("gwtAppTitle").add(titleLabel);
   ...
   }
}

国際化-完全な例

この例では、簡単な手順でGWTアプリケーションの国際化機能を示します。

次の手順に従って、_GWTで作成したGWTアプリケーションを更新します-アプリケーションの作成_の章-

Step Description
1 Create a project with a name HelloWorld under a package com.finddevguides as explained in the GWT - Create Application chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorldl and HelloWorld.java as explained below. Keep rest of the files unchanged.
3 Compile and run the application to verify the result of the implemented logic.

以下は、変更されたモジュール記述子 src/com.finddevguides/HelloWorld.gwt.xml の内容です。

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to = 'helloworld'>
  <!-- Inherit the core Web Toolkit stuff.                        -->
  <inherits name = 'com.google.gwt.user.User'/>

  <!-- Inherit the default GWT style sheet.                       -->
  <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>

  <!-- Specify the app entry point class.                         -->
  <entry-point class = 'com.finddevguides.client.HelloWorld'/>
  <extend-property name = "locale" values="de"/>
  <!-- Specify the paths for translatable code                    -->
  <source path = 'client'/>
  <source path = 'shared'/>

</module>

以下は、変更されたスタイルシートファイル war/HelloWorld.css の内容です。

body {
   text-align: center;
   font-family: verdana, sans-serif;
}

h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-align: center;
}

以下は、変更されたHTMLホストファイル war/HelloWorldl の内容です。

<html>
   <head>
      <title>Hello World</title>
      <link rel = "stylesheet" href = "HelloWorld.css"/>
      <script language = "javascript" src = "helloworld/helloworld.nocache.js">
      </script>
   </head>
   <body>

      <h1 id = "gwtAppTitle"></h1>
      <div id = "gwtContainer"></div>

   </body>
</html>
*src/com.finddevguides/client* パッケージにHelloWorldMessages.propertiesファイルを作成し、次のコンテンツをその中に配置します
enterName = Enter your name
clickMe = Click Me
applicationTitle = Application Internationalization Demonstration
greeting = Hello {0}
*src/com.finddevguides/client* パッケージにHelloWorldMessages_de.propertiesファイルを作成し、次のコンテンツをその中に配置します
enterName = Geben Sie Ihren Namen
clickMe = Klick mich
applicationTitle = Anwendung Internationalisierung Demonstration
greeting = Hallo {0}
*src/com.finddevguides/client* パッケージにHelloWorldMessages.javaクラスを作成し、次のコンテンツをその中に配置します
package com.finddevguides.client;
import com.google.gwt.i18n.client.Messages;

public interface HelloWorldMessages extends Messages {
   @DefaultMessage("Enter your name")
   String enterName();

   @DefaultMessage("Click Me")
   String clickMe();

   @DefaultMessage("Application Internationalization Demonstration")
   String applicationTitle();

   @DefaultMessage("Hello {0}")
   String greeting(String name);
}

Javaファイル src/com.finddevguides/HelloWorld.java の以下のコンテンツを使用して、GWTコードの国際化機能を示します。

package com.finddevguides.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class HelloWorld implements EntryPoint {

  /*create an object of HelloWorldMessages interface
      using GWT.create() method*/
   private HelloWorldMessages messages =
   GWT.create(HelloWorldMessages.class);

   public void onModuleLoad() {
     /*create UI */
      final TextBox txtName = new TextBox();
      txtName.setWidth("200");
      txtName.addKeyUpHandler(new KeyUpHandler() {
         @Override
         public void onKeyUp(KeyUpEvent event) {
            if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER){
               Window.alert(getGreeting(txtName.getValue()));
            }
         }
      });
      Label lblName = new Label(messages.enterName() + ": ");

      Button buttonMessage = new Button(messages.clickMe() + "!");

      buttonMessage.addClickHandler(new ClickHandler() {
         @Override
         public void onClick(ClickEvent event) {
            Window.alert(getGreeting(txtName.getValue()));
         }
      });

      HorizontalPanel hPanel = new HorizontalPanel();
      hPanel.add(lblName);
      hPanel.add(txtName);

      VerticalPanel vPanel = new VerticalPanel();
      vPanel.setSpacing(10);
      vPanel.add(hPanel);
      vPanel.add(buttonMessage);
      vPanel.setCellHorizontalAlignment(buttonMessage,
      HasHorizontalAlignment.ALIGN_RIGHT);

      DecoratorPanel panel = new DecoratorPanel();
      panel.add(vPanel);
      Label titleLabel = new Label(messages.applicationTitle());
     //Add title to the application
      RootPanel.get("gwtAppTitle").add(titleLabel);
     //Add widgets to the root panel.
      RootPanel.get("gwtContainer").add(panel);
   }

   public String getGreeting(String name){
      return messages.greeting(name + "!");
   }
}

すべての変更が完了したら、link:/gwt/gwt_create_application [GWT-アプリケーションの作成]の章で行ったように、アプリケーションをコンパイルして開発モードで実行します。 すべてがあなたのアプリケーションでうまくいけば、これは次の結果を生成します-

GWT国際化デモ

次に、URLを更新してlocale = de.Set URL-_http://127.0.0.1:8888/HelloWorldl?gwt.codesvr = 127.0.0.1:9997 &locale = de _を含めます。 すべてがあなたのアプリケーションでうまくいけば、これは次の結果を生成します-

GWTインターンドイツ語

GWT-履歴クラス

GWTアプリケーションは通常、JavaScriptを実行する単一ページのアプリケーションであり、多くのページを含まないため、ブラウザーはユーザーとアプリケーションとの対話を追跡しません。 ブラウザの履歴機能を使用するには、アプリケーションはナビゲーション可能なページごとに一意のURLフラグメントを生成する必要があります。

GWTは、この状況を処理するための*履歴メカニズム*を提供します。

GWTは、*トークン*という用語を使用します。これは、アプリケーションが特定の状態に戻るために解析できる単なる文字列です。 アプリケーションはこのトークンをブラウザーの履歴にURLフラグメントとして保存します。

たとえば、「pageIndex1」という名前の履歴トークンは次のようにURLに追加されます-

http://www.finddevguides.com/HelloWorldl#pageIndex0

履歴管理ワークフロー

ステップ1-履歴サポートを有効にする

GWT Historyサポートを使用するには、最初に次のiframeをホストHTMLページに埋め込む必要があります。

<iframe src = "javascript:''"
   id = "__gwt_historyFrame"
   style = "width:0;height:0;border:0"></iframe>

ステップ2-トークンを履歴に追加する

次の例の統計は、ブラウザの履歴にトークンを追加する方法を示しています

int index = 0;
History.newItem("pageIndex" + index);

ステップ3-履歴からトークンを取得する

ユーザーがブラウザの戻る/進むボタンを使用すると、トークンを取得し、それに応じてアプリケーションの状態を更新します。

History.addValueChangeHandler(new ValueChangeHandler<String>() {
   @Override
   public void onValueChange(ValueChangeEvent<String> event) {
      String historyToken = event.getValue();
     /*parse the history token*/
      try {
         if (historyToken.substring(0, 9).equals("pageIndex")) {
            String tabIndexToken = historyToken.substring(9, 10);
            int tabIndex = Integer.parseInt(tabIndexToken);
           /*select the specified tab panel*/
            tabPanel.selectTab(tabIndex);
         } else {
            tabPanel.selectTab(0);
         }
      } catch (IndexOutOfBoundsException e) {
         tabPanel.selectTab(0);
      }
   }
});

次に、動作中の履歴クラスを見てみましょう。

履歴クラス-完全な例

この例では、簡単な手順でGWTアプリケーションの履歴管理を説明します。 次の手順に従って、_GWTで作成したGWTアプリケーションを更新します-アプリケーションの作成_の章-

Step Description
1 Create a project with a name HelloWorld under a package com.finddevguides as explained in the GWT - Create Application chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorldl and HelloWorld.java as explained below. Keep rest of the files unchanged.
3 Compile and run the application to verify the result of the implemented logic.

以下は、変更されたモジュール記述子 src/com.finddevguides/HelloWorld.gwt.xml の内容です。

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to = 'helloworld'>
   <!-- Inherit the core Web Toolkit stuff.                        -->
   <inherits name = 'com.google.gwt.user.User'/>

   <!-- Inherit the default GWT style sheet.                       -->
   <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>

   <!-- Specify the app entry point class.                         -->
   <entry-point class = 'com.finddevguides.client.HelloWorld'/>
   <!-- Specify the paths for translatable code                    -->
   <source path = 'client'/>
   <source path = 'shared'/>

</module>

以下は、変更されたスタイルシートファイル war/HelloWorld.css の内容です。

body {
   text-align: center;
   font-family: verdana, sans-serif;
}

h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-align: center;
}

以下は、変更されたHTMLホストファイル war/HelloWorldl の内容です。

<html>
   <head>
      <title>Hello World</title>
      <link rel = "stylesheet" href = "HelloWorld.css"/>
      <script language = "javascript" src = "helloworld/helloworld.nocache.js">
      </script>
   </head>

   <body>
      <iframe src = "javascript:''"id = "__gwt_historyFrame"
         style = "width:0;height:0;border:0"></iframe>
      <h1> History Class Demonstration</h1>
      <div id = "gwtContainer"></div>
   </body>
</html>

Javaファイル src/com.finddevguides/HelloWorld.java の次の内容を使用して、GWTコードでの履歴管理のデモを行います。

package com.finddevguides.client;

import com.google.gwt.core.client.EntryPoint;

import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;

import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TabPanel;

public class HelloWorld implements EntryPoint {

  /**
 *This is the entry point method.
   */
   public void onModuleLoad() {
     /*create a tab panel to carry multiple pages*/
      final TabPanel tabPanel = new TabPanel();

     /*create pages*/
      HTML firstPage = new HTML("<h1>We are on first Page.</h1>");
      HTML secondPage = new HTML("<h1>We are on second Page.</h1>");
      HTML thirdPage = new HTML("<h1>We are on third Page.</h1>");

      String firstPageTitle = "First Page";
      String secondPageTitle = "Second Page";
      String thirdPageTitle = "Third Page";
      tabPanel.setWidth("400");

     /* add pages to tabPanel*/
      tabPanel.add(firstPage, firstPageTitle);
      tabPanel.add(secondPage,secondPageTitle);
      tabPanel.add(thirdPage, thirdPageTitle);

     /*add tab selection handler*/
      tabPanel.addSelectionHandler(new SelectionHandler<Integer>() {
         @Override
         public void onSelection(SelectionEvent<Integer> event) {
           /*add a token to history containing pageIndex
             History class will change the URL of application
             by appending the token to it.
           */
            History.newItem("pageIndex" + event.getSelectedItem());
         }
      });

     /*add value change handler to History
       this method will be called, when browser's
       Back button or Forward button are clicked
       and URL of application changes.
      */
      History.addValueChangeHandler(new ValueChangeHandler<String>() {
         @Override
         public void onValueChange(ValueChangeEvent<String> event) {
            String historyToken = event.getValue();
           /*parse the history token*/
            try {
               if (historyToken.substring(0, 9).equals("pageIndex")) {
                  String tabIndexToken = historyToken.substring(9, 10);
                  int tabIndex = Integer.parseInt(tabIndexToken);
                 /*select the specified tab panel*/
                  tabPanel.selectTab(tabIndex);
               } else {
                  tabPanel.selectTab(0);
               }
            } catch (IndexOutOfBoundsException e) {
               tabPanel.selectTab(0);
            }
         }
      });

     /*select the first tab by default*/
      tabPanel.selectTab(0);

     /*add controls to RootPanel*/
      RootPanel.get().add(tabPanel);
   }
}

すべての変更が完了したら、link:/gwt/gwt_create_application [GWT-アプリケーションの作成]の章で行ったように、アプリケーションをコンパイルして開発モードで実行します。 すべてがあなたのアプリケーションでうまくいけば、これは次の結果を生成します-

GWT History Demo

  • 各タブをクリックして、異なるページを選択します。
  • 各タブを選択すると、アプリケーションのURLが変更され、#pageIndexがURLに追加されることに注意してください。
  • ブラウザの戻るボタンと進むボタンが有効になっていることも確認できます。
  • ブラウザの「戻る」ボタンと「進む」ボタンを使用すると、それに応じて異なるタブが選択されます。

GWT-ブックマークのサポート

GWTは、_GWT-History Class_章を参照できるHistoryクラスを使用したブラウザー履歴管理をサポートしています。

GWTは、*トークン*という用語を使用します。これは、アプリケーションが特定の状態に戻るために解析できる単なる文字列です。 アプリケーションはこのトークンをブラウザーの履歴にURLフラグメントとして保存します。

_GWT-履歴クラス_の章では、コードを記述することにより、トークンの作成と履歴での設定を処理します。

この記事では、トークンの作成と履歴管理を自動的に行い、ブックマークのアプリケーション機能を提供する特別なウィジェットHyperlinkについて説明します。

ブックマークの例

この例では、簡単な手順でGWTアプリケーションのブックマークを示します。

_GWT-Create Application_の章で作成したGWTアプリケーションを更新するための次の手順-

Step Description
1 Create a project with a name HelloWorld under a package com.finddevguides as explained in the GWT - Create Application chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorldl and HelloWorld.java as explained below. Keep rest of the files unchanged.
3 Compile and run the application to verify the result of the implemented logic.

以下は、変更されたモジュール記述子 src/com.finddevguides/HelloWorld.gwt.xml の内容です。

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to = 'helloworld'>
   <!-- Inherit the core Web Toolkit stuff.                        -->
   <inherits name = 'com.google.gwt.user.User'/>

   <!-- Inherit the default GWT style sheet.                       -->
   <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>

   <!-- Specify the app entry point class.                         -->
   <entry-point class = 'com.finddevguides.client.HelloWorld'/>
   <!-- Specify the paths for translatable code                    -->
   <source path = 'client'/>
   <source path = 'shared'/>

</module>

以下は、変更されたスタイルシートファイル war/HelloWorld.css の内容です。

body {
   text-align: center;
   font-family: verdana, sans-serif;
}

h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-align: center;
}

以下は、変更されたHTMLホストファイル war/HelloWorldl の内容です。

<html>
   <head>
      <title>Hello World</title>
      <link rel = "stylesheet" href = "HelloWorld.css"/>
      <script language = "javascript" src = "helloworld/helloworld.nocache.js">
      </script>
   </head>

   <body>
      <iframe src = "javascript:''"id = "__gwt_historyFrame"
         style = "width:0;height:0;border:0"></iframe>
      <h1> Bookmarking Demonstration</h1>
      <div id = "gwtContainer"></div>
   </body>
</html>

Javaファイル src/com.finddevguides/HelloWorld.java の以下のコンテンツを使用して、GWTコードでのブックマークのデモを行います。

package com.finddevguides.client;

import com.google.gwt.core.client.EntryPoint;

import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;

import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

public class HelloWorld implements EntryPoint {

   private TabPanel tabPanel;

   private void selectTab(String historyToken){
     /*parse the history token*/
      try {
         if (historyToken.substring(0, 9).equals("pageIndex")) {
            String tabIndexToken = historyToken.substring(9, 10);
            int tabIndex = Integer.parseInt(tabIndexToken);
           /*Select the specified tab panel*/
            tabPanel.selectTab(tabIndex);
         } else {
            tabPanel.selectTab(0);
         }
      } catch (IndexOutOfBoundsException e) {
         tabPanel.selectTab(0);
      }
   }

  /**
 *This is the entry point method.
   */
   public void onModuleLoad() {
     /*create a tab panel to carry multiple pages*/
      tabPanel = new TabPanel();

     /*create pages*/
      HTML firstPage = new HTML("<h1>We are on first Page.</h1>");
      HTML secondPage = new HTML("<h1>We are on second Page.</h1>");
      HTML thirdPage = new HTML("<h1>We are on third Page.</h1>");

      String firstPageTitle = "First Page";
      String secondPageTitle = "Second Page";
      String thirdPageTitle = "Third Page";

      Hyperlink firstPageLink = new Hyperlink("1", "pageIndex0");
      Hyperlink secondPageLink = new Hyperlink("2", "pageIndex1");
      Hyperlink thirdPageLink = new Hyperlink("3", "pageIndex2");

      HorizontalPanel linksHPanel = new HorizontalPanel();
      linksHPanel.setSpacing(10);
      linksHPanel.add(firstPageLink);
      linksHPanel.add(secondPageLink);
      linksHPanel.add(thirdPageLink);

     /*If the application starts with no history token,
         redirect to a pageIndex0*/
      String initToken = History.getToken();

      if (initToken.length() == 0) {
         History.newItem("pageIndex0");
         initToken = "pageIndex0";
      }

      tabPanel.setWidth("400");
     /* add pages to tabPanel*/
      tabPanel.add(firstPage, firstPageTitle);
      tabPanel.add(secondPage,secondPageTitle);
      tabPanel.add(thirdPage, thirdPageTitle);

     /*add value change handler to History
      * this method will be called, when browser's Back button
 *or Forward button are clicked.
      * and URL of application changes.
       * */
      History.addValueChangeHandler(new ValueChangeHandler<String>() {
         @Override
         public void onValueChange(ValueChangeEvent<String> event) {
            selectTab(event.getValue());
         }
      });

      selectTab(initToken);

      VerticalPanel vPanel = new VerticalPanel();

      vPanel.setSpacing(10);
      vPanel.add(tabPanel);
      vPanel.add(linksHPanel);

     /*add controls to RootPanel*/
      RootPanel.get().add(vPanel);
   }
}

すべての変更が完了したら、link:/gwt/gwt_create_application [GWT-アプリケーションの作成]の章で行ったように、アプリケーションをコンパイルして開発モードで実行します。 すべてがあなたのアプリケーションでうまくいけば、これは次の結果を生成します-

GWTブックマークデモ

  • 1、2、または3をクリックします。 インデックスによってタブが変わることがわかります。
  • 1、2、または3をクリックすると、アプリケーションのURLが変更され、#pageIndexがURLに追加されます。
  • ブラウザの戻るボタンと進むボタンが有効になっていることも確認できます。
  • ブラウザの「戻る」ボタンと「進む」ボタンを使用すると、それに応じて異なるタブが選択されます。
  • 1、2、または3を右クリックします。 開く、新しいウィンドウで開く、新しいタブで開く、お気に入りに追加などのオプションを表示できます。
  • 3を右クリックします。 お気に入りに追加を選択します。 ブックマークをページ3として保存します。
  • お気に入りを開き、ページ3を選択します。 3番目のタブが選択されています。

GWT-ロギングフレームワーク

ロギングフレームワークはjava.util.loggingをエミュレートするため、サーバー側のロギングコードと同じ構文を使用し、同じ動作をします

GWTロギングは、.gwt.xmlファイルを使用して構成されます。

ロギングを有効/無効に設定できます。特定のハンドラを有効/無効にし、デフォルトのログレベルを変更できます。

ロガーの種類

ロガーはツリー構造で編成され、ルートロガーはツリーのルートにあります。

ロガーの名前は、*。*を使用して名前のセクションを区切って親/子関係を決定します。

例として、Hospital.room1とHospital.room2の2つのロガーがある場合、それらは兄弟であり、親はHospitalという名前のロガーです。 病院ロガー(およびドット「。」を含まない名前のロガー)は、ルートロガーを親として持っています。

private static Logger room1Logger = Logger.getLogger("Hospital.room1");
private static Logger room2Logger = Logger.getLogger("Hospital.room2");
private static Logger hospitalLogger = Logger.getLogger("Hospital");
private static Logger rootLogger = Logger.getLogger("");

ログハンドラー

GWTは、ロガーを使用して作成されたログエントリを表示するデフォルトハンドラーを提供します。

Handler Logs to Description
SystemLogHandler stdout These messages can only be seen in Development Mode in the DevMode window.
DevelopmentModeLogHandler DevMode Window Logs by calling method GWT.log. These messages can only be seen in Development Mode in the DevMode window.
ConsoleLogHandler javascript console Logs to the javascript console, which is used by Firebug Lite (for IE), Safari and Chrome.
FirebugLogHandler Firebug Logs to the firebug console.
PopupLogHandler popup Logs to the popup which resides in the upper left hand corner of application when this handler is enabled.
SimpleRemoteLogHandler server This handler sends log messages to the server, where they will be logged using the server side logging mechanism.

GWTアプリケーションでロギングを構成する

HelloWorld.gwt.xmlファイルは、次のようにGWTロギングを有効にするように構成されます-

# add logging module
   <inherits name = "com.google.gwt.logging.Logging"/>
# To change the default logLevel
   <set-property name = "gwt.logging.logLevel" value = "SEVERE"/>
# To enable logging
   <set-property name = "gwt.logging.enabled" value = "TRUE"/>
# To disable a popup Handler
   <set-property name = "gwt.logging.popupHandler" value = "DISABLED"/>

ロガーを使用してユーザーアクションを記録する

/*Create Root Logger*/
private static Logger rootLogger = Logger.getLogger("");
...
rootLogger.log(Level.SEVERE, "pageIndex selected: " + event.getValue());
...

ロギングフレームワークの例

この例では、GWTアプリケーションのロギング機能を示す簡単な手順を紹介します。 次の手順に従って、_GWTで作成したGWTアプリケーションを更新します-アプリケーションの作成_の章-

Step Description
1 Create a project with a name HelloWorld under a package com.finddevguides as explained in the GWT - Create Application chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorldl and HelloWorld.java as explained below. Keep rest of the files unchanged.
3 Compile and run the application to verify the result of the implemented logic.

以下は、変更されたモジュール記述子 src/com.finddevguides/HelloWorld.gwt.xml の内容です。

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to = 'helloworld'>
   <!-- Inherit the core Web Toolkit stuff.                        -->
   <inherits name = 'com.google.gwt.user.User'/>

   <!-- Inherit the default GWT style sheet.                       -->
   <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>
   <inherits name = "com.google.gwt.logging.Logging"/>
   <!-- Specify the app entry point class.                         -->
   <entry-point class = 'com.finddevguides.client.HelloWorld'/>
   <!-- Specify the paths for translatable code                    -->
   <source path = 'client'/>
   <source path = 'shared'/>
   <set-property name = "gwt.logging.logLevel" value="SEVERE"/>
   <set-property name = "gwt.logging.enabled" value = "TRUE"/>
   <set-property name = "gwt.logging.popupHandler" value=  "DISABLED"/>
</module>

以下は、変更されたスタイルシートファイル war/HelloWorld.css の内容です。

body {
   text-align: center;
   font-family: verdana, sans-serif;
}

h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-align: center;
}

以下は、変更されたHTMLホストファイル war/HelloWorldl の内容です。

<html>
   <head>
      <title>Hello World</title>
      <link rel = "stylesheet" href = "HelloWorld.css"/>
      <script language = "javascript" src = "helloworld/helloworld.nocache.js">
      </script>
   </head>

   <body>
      <iframe src = "javascript:''"id = "__gwt_historyFrame"
         style = "width:0;height:0;border:0"></iframe>
      <h1> Logging Demonstration</h1>
      <div id = "gwtContainer"></div>
   </body>
</html>

Javaファイル src/com.finddevguides/HelloWorld.java の以下のコンテンツを使用して、GWTコードでのブックマークのデモを行います。

package com.finddevguides.client;

import java.util.logging.Level;
import java.util.logging.Logger;

import com.google.gwt.core.client.EntryPoint;

import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;

import com.google.gwt.logging.client.HasWidgetsLogHandler;

import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

public class HelloWorld implements EntryPoint {

   private TabPanel tabPanel;
  /*Create Root Logger*/
   private static Logger rootLogger = Logger.getLogger("");
   private VerticalPanel customLogArea;

   private void selectTab(String historyToken){
     /*parse the history token*/
      try {
         if (historyToken.substring(0, 9).equals("pageIndex")) {
            String tabIndexToken = historyToken.substring(9, 10);
            int tabIndex = Integer.parseInt(tabIndexToken);
           /*Select the specified tab panel*/
            tabPanel.selectTab(tabIndex);
         } else {
            tabPanel.selectTab(0);
         }
      } catch (IndexOutOfBoundsException e) {
         tabPanel.selectTab(0);
      }
   }

  /**
 *This is the entry point method.
   */
   public void onModuleLoad() {
     /*create a tab panel to carry multiple pages*/
      tabPanel = new TabPanel();

     /*create pages*/
      HTML firstPage = new HTML("<h1>We are on first Page.</h1>");
      HTML secondPage = new HTML("<h1>We are on second Page.</h1>");
      HTML thirdPage = new HTML("<h1>We are on third Page.</h1>");

      String firstPageTitle = "First Page";
      String secondPageTitle = "Second Page";
      String thirdPageTitle = "Third Page";

      Hyperlink firstPageLink = new Hyperlink("1", "pageIndex0");
      Hyperlink secondPageLink = new Hyperlink("2", "pageIndex1");
      Hyperlink thirdPageLink = new Hyperlink("3", "pageIndex2");

      HorizontalPanel linksHPanel = new HorizontalPanel();
      linksHPanel.setSpacing(10);
      linksHPanel.add(firstPageLink);
      linksHPanel.add(secondPageLink);
      linksHPanel.add(thirdPageLink);

     /*If the application starts with no history token,
         redirect to a pageIndex0*/
      String initToken = History.getToken();

      if (initToken.length() == 0) {
         History.newItem("pageIndex0");
         initToken = "pageIndex0";
      }

      tabPanel.setWidth("400");
     /* add pages to tabPanel*/
      tabPanel.add(firstPage, firstPageTitle);
      tabPanel.add(secondPage,secondPageTitle);
      tabPanel.add(thirdPage, thirdPageTitle);

     /*add value change handler to History
      * this method will be called, when browser's Back button
 *or Forward button are clicked.
      * and URL of application changes.
       * */
      History.addValueChangeHandler(new ValueChangeHandler<String>() {
         @Override
         public void onValueChange(ValueChangeEvent<String> event) {
            selectTab(event.getValue());
            rootLogger.log(Level.SEVERE, "pageIndex selected: "
            + event.getValue());
         }
      });

      selectTab(initToken);

      VerticalPanel vPanel = new VerticalPanel();

      vPanel.setSpacing(10);
      vPanel.add(tabPanel);
      vPanel.add(linksHPanel);

      customLogArea = new VerticalPanel();
      vPanel.add(customLogArea);

     /*an example of using own custom logging area.*/
      rootLogger.addHandler(new HasWidgetsLogHandler(customLogArea));

     /*add controls to RootPanel*/
      RootPanel.get().add(vPanel);
   }
}

すべての変更が完了したら、link:/gwt/gwt_create_application [GWT-アプリケーションの作成]の章で行ったように、アプリケーションをコンパイルして開発モードで実行します。 すべてがあなたのアプリケーションでうまくいけば、これは次の結果を生成します-

GWT Logging Demo

1、2、または3をクリックします。 1,2または3をクリックすると、pageIndexを表示してログが印刷されていることがわかります。 Eclipseでコンソール出力を確認します。 Eclipseコンソールでもログが印刷されていることがわかります。

Fri Aug 31 11:42:35 IST 2012
SEVERE: pageIndex selected: pageIndex0
Fri Aug 31 11:42:37 IST 2012
SEVERE: pageIndex selected: pageIndex1
Fri Aug 31 11:42:38 IST 2012
SEVERE: pageIndex selected: pageIndex2
Fri Aug 31 11:42:40 IST 2012
SEVERE: pageIndex selected: pageIndex0
Fri Aug 31 11:42:41 IST 2012
SEVERE: pageIndex selected: pageIndex1
Fri Aug 31 11:42:41 IST 2012
SEVERE: pageIndex selected: pageIndex2

モジュール記述子 src/com.finddevguides/HelloWorld.gwt.xml を更新して、popupHandlerを有効にします。

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to = 'helloworld'>
  <!-- Inherit the core Web Toolkit stuff.                        -->
   <inherits name = 'com.google.gwt.user.User'/>

   <!-- Inherit the default GWT style sheet.                       -->
   <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>
   <inherits name = "com.google.gwt.logging.Logging"/>
   <!-- Specify the app entry point class.                         -->
   <entry-point class = 'com.finddevguides.client.HelloWorld'/>
   <!-- Specify the paths for translatable code                    -->
   <source path = 'client'/>
   <source path = 'shared'/>
   <set-property name = "gwt.logging.logLevel" value = "SEVERE"/>
   <set-property name = "gwt.logging.enabled" value = "TRUE"/>
   <set-property name="gwt.logging.popupHandler" value = "ENABLED"/>
</module>

すべての変更が完了したら、ブラウザウィンドウを更新してアプリケーションをリロードします(ブラウザのF5/リロードボタンを押します)。 アプリケーションの左上隅にポップアップウィンドウが表示されます。

1、2、または3をクリックします。 1,2または3をクリックすると、ポップアップウィンドウにpageIndexを表示してログが印刷されているのがわかります。

GWT Popup Logging Demo Gwt-questions-answers