blob: 990ade90e36aeccf58b2a9418e6a9f090708b346 [file] [log] [blame]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><link rel="stylesheet" href="../../../print.css" type="text/css" media="print">
<title>RESTful Webサービスについて - NetBeans IDEチュートリアル</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="KEYWORDS" content="NETBEANS, TUTORIAL, GUIDE, USER, DOCUMENTATION, WEB SERVICE, WEB SERVICES, REST, RESTFUL">
<meta name="description"
content="This tutorial shows how to use NetBeans IDE
to work with RESTful web services.">
<link rel="stylesheet" href="../../../netbeans.css"></head>
<body>
<h1>RESTful Webサービスについて</h1>
<p>REST (REpresentational State Transfer)は、World Wide Webなどの分散ハイパーメディア・システム用アーキテクチャ・スタイルです。RESTfulアーキテクチャで中心となるのは、URI (Universal Resource Identifier)によって識別されるリソースという概念です。これらのリソースはHTTPなどの標準インタフェースを使用して操作でき、情報はこれらのリソースの表現を使用して交換されます。このチュートリアルでは、最初にRESTについて少し学習した後、NetBeans IDEがこのアーキテクチャ・スタイルをサポートする方法について説明します。</p>
<p><b>目次</b></p>
<img alt="このページの内容は、NetBeans IDE 7.2、7.3、7.4および8.0に適用されます" class="stamp" src="../../../images_www/articles/73/netbeans-stamp-80-74-73.png" title="このページの内容は、NetBeans IDE 7.2、7.3、7.4および8.0に適用されます">
<ul>
<!-- <li><a href="#introduction">Exercise 0: Install and configure the tutorial environment</a></li>-->
<li><a href="#introduction"> 概要</a></li>
<li><a href="#entity-classes">RESTful Webサービス、永続性およびエンティティ・クラス</a></li>
<li><a href="#create-services-from-db">データベースからのRESTful Webサービスの作成</a>
<ul>
<li><a href="#create-project">プロジェクトの作成</a></li>
<li><a href="#entities-and-services">エンティティ・クラスとRESTfulサービスの生成</a></li>
</ul></li>
<li><a href="#test-rest">RESTful Webサービスのテスト</a></li>
<!-- <li><a href="#add-google-map">
Adding a Google Map Feature</a></li>-->
<!-- <li><a href="#rest-spring">RESTful Web Services in the Spring Framework</a>
<ul>
<li><a href="#create-spring-webapp">Creating a Java Web Application
With the Spring Framework</a></li>
<li><a href="#add-aopalliance">Adding aopalliance.jar to the Project</a></li>
<li><a href="#create-spring-restful-services">Creating RESTful Services in
the Spring-enabled Project</a></li>
<li><a href="#spring-errors">Compilation Errors</a></li>
</ul>
</li>-->
</ul>
<p><b>このチュートリアルに従うには、次のソフトウェアとリソースが必要です。</b></p>
<table>
<tbody>
<tr>
<th class="tblheader" scope="col">ソフトウェアまたはリソース</th>
<th class="tblheader" scope="col">必須バージョン</th>
</tr>
<tr>
<td class="tbltd1"><a href="https://netbeans.org/downloads/index.html" target="_blank">NetBeans IDE</a></td>
<td class="tbltd1">Java EEダウンロード・バンドル</td>
</tr>
<tr>
<td class="tbltd1"><a href="http://www.oracle.com/technetwork/java/javase/downloads/index.html" target="_blank">Java Development Kit (JDK)</a></td>
<td class="tbltd1">バージョン7または8</td>
</tr>
<tr>
<td class="tbltd1">Java EE互換のアプリケーション・サーバー</td>
<td class="tbltd1"><p><a href="http://www.oracle.com/technetwork/middleware/weblogic/overview/index.html" target="_blank">Oracle WebLogic Server 11g-12c</a><br>またはGlassFish Server Open Source Edition 3.xまたは4.x<br> (EJBサポート・プラグインがTomcatにインストールされていないかぎりTomcatでは動作しません)</p>
</tr>
<tr>
<td class="tbltd1"><p>jdbc/sampleデータベース - <br> Java DB (Derby)データベース・サーバーまたはMySQL<br>データベース・サーバー </p></td>
<td class="tbltd1"><p>Java DB (Derby)の場合、jdbc/sampleデータベースはNetBeans IDEによって生成され、<br>そのタイミングはIDEとGlassFishアプリケーション・サーバーをインストールしたときです。</p>
<p>MySQLの場合、IDE内からMySQLサーバー上でサンプル・データベースを作成した後、IDEはサンプル・データベースにデータを生成します。 </p></td>
</tr>
</tbody>
</table>
<p class="notes">GlassFishサーバーは、どちらもNetBeans IDEのWebおよびJava EEの配布とともにインストールできます。または、<a href="https://glassfish.java.net/download.html">GlassFishサーバーのダウンロード・ページ</a>にアクセスしてください。</p>
<p class="alert"><strong>重要: </strong>Java EE 6およびJava EE 7プロジェクトには、GlassFish ServerまたはOracle WebLogic Server 12cが必要です。</p>
<!-- =========================================== -->
<h2><a name="introduction"></a> 概要</h2>
<p>RESTful Webサービスは、RESTfulアーキテクチャ・スタイルを使用してビルドされたサービスです。RESTfulアプローチを使用するWebサービスのビルドは、インターネット上にサービスをデプロイするために、SOAPベースのテクノロジを使用するかわりとして幅広く使用されています。これは、軽量かつHTTP経由でデータを直接送信できるためです。</p>
<p>IDEは、JAX-RS (JSR 311 - Java API for RESTful Web Services)およびJersey (JAX-RSのリファレンス実装)を使用する、RESTful Webサービスの迅速な開発をサポートしています。</p>
<p>詳細は、次を参照してください。</p>
<ul>
<li><a href="http://jcp.org/en/jsr/detail?id=311" target="_blank">JSR 311: JAX-RS: The Java API for RESTful Web Services</a>
<li><a href="http://jersey.dev.java.net/">Jersey, the open source JAX-RS (JSR 311) Reference Implementation for building RESTful Web services</a>
</ul>
<p>RESTful Webサービスのビルドに加え、IDEは、テスト、RESTful Webサービスにアクセスするクライアント・アプリケーションのビルド、およびWebサービスを呼び出すコードの生成(RESTfulとSOAPベースの両方)もサポートしています。</p>
<p>IDEが提供するRESTful機能の一覧は次のとおりです。</p>
<ol>
<li>JPAエンティティ・クラスおよびパターンからのRESTful Webサービスの迅速な作成。</li>
<li>「サービス」ウィンドウのWebサービス・マネージャからコンポーネントをドラッグ・アンド・ドロップすることによる、Googleマップ、Yahoo News Search、StrikeIron WebサービスなどのWebサービスを呼び出すコードの迅速な生成。</li>
<li>Webサービス・マネージャに登録されたサービスに対するRESTful Javaクライアントの生成。</li>
<li>RESTful Webサービスのテスト用テスト・クライアントの生成。</li>
<li>プロジェクト内のRESTful Webサービスの実装クラスを簡単にナビゲートする論理ビュー。</li>
<!--<li> Fully integrated Spring framework, providing Spring transaction handling.</li>-->
</ol>
<p>このチュートリアルでは、RESTful Webサービスを生成、実装、およびテストする際、IDEがどのようなサポートを提供するのかを説明します。</p>
<!-- =========================================== -->
<h2><a name="entity-classes"></a> RESTful Webサービス、永続性およびエンティティ・クラス </h2>
<p>JavaにおけるRESTful Webサービスは、データベースと通信するために<a href="http://en.wikipedia.org/wiki/Java_Persistence_API" target="_blank">Java Persistence API</a>に依存しています。具体的には、RESTful WebサービスはPersistence APIに定義されるように<em>エンティティ・クラス</em><em>永続性ユニット</em>に依存しています。エンティティ・クラスはリレーショナル・データベース内のオブジェクトに対応するJavaクラスです。<a href="http://download.oracle.com/javaee/5/tutorial/doc/bnbqa.html" target="_blank">Java EE5チュートリアル</a>には次のように記載されています。「エンティティは軽量な永続性ドメイン・オブジェクトです。一般的に、エンティティはリレーショナル・データベースの表を表現し、各エンティティ・インスタンスはその表の行に相当します。」永続性ユニットは、<tt>persistence.xml</tt>ファイルで定義されるように、一連のエンティティ・クラス、データ・ソース、永続性プロバイダ、および永続性ユニットの独自の名前で構成されます。 </p>
<p>NetBeans IDEを使用して、エンティティ・クラスとRESTful Webサービスを同じプロセスで作成することも、既存のエンティティ・クラスからRESTful Webサービスを作成することもできます。このチュートリアルでは、データベースからのRESTfulサービス・ウィザードを使用して、エンティティ・クラスとRESTful Webサービスを同じプロセスで生成します。ウィザードは永続性ユニットを自動的に生成します。</p>
<!-- =========================================== -->
<h2><a name="mysql"></a>MySQLデータベース・サーバーの使用 </h2>
<p>JavaDB (Derby)でなくMySQLデータベース・サーバーを使用する場合、データベース・サーバーをIDEに登録し、<tt>sample</tt>データベースをサーバーに追加する必要があります。</p>
<p><strong>このチュートリアルでMySQLデータベース・サーバーを使用するには:</strong></p>
<ol>
<li>MySQLサーバーがまだ登録されていない場合、サーバーをIDEに登録します。MySQLサーバーを登録するには、IDEの「サービス」ウィンドウに移動し、「データベース」ノードを右クリックして「MySQLサーバーを登録」を選択します。<br> <img alt="「サービス」ウィンドウの「MySQLサーバーを登録」オプション" class="margin-around b-bottom" src="../../../images_www/articles/72/websvc/rest/register-mysql-server.png"></li>
<li>
<p>管理者のユーザー名やパスワードなどのMySQLサーバーの構成の詳細情報を入力するダイアログが開きます。<a href="../ide/install-and-configure-mysql-server.html">MySQLデータベースへの接続</a>のMySQLサーバー・プロパティの構成を参照してください。</p>
<img alt="IDEで登録中のMySQLサーバーの基本プロパティ" class="margin-around" src="../../../images_www/articles/72/websvc/rest/basic-mysql-properties.png"></li>
<li>MySQLサーバーを起動し、これに接続します。<a href="../ide/install-and-configure-mysql-server.html">MySQLデータベースへの接続</a>のMySQLサーバーの起動を参照してください。 </li>
<li>MySQLサーバーのノードを右クリックし、「データベースを作成」を選択します。「MySQLデータベースの作成」ダイアログが開きます。<br> <img alt="「データベースを作成」コンテキスト・メニュー・オプション" class="margin-around b-bottom" src="../../../images_www/articles/72/websvc/rest/create-database.png"> </li>
<li>新規データベース名として「<tt>sample</tt>」と入力します。rootユーザーまたは選択したユーザーにフル・アクセス権を付与します。<br> <img alt="入力された「新規データベース名」ダイアログ" class="margin-around" src="../../../images_www/articles/72/websvc/rest/new-database-name.png"> </li>
<li>「OK」をクリックします。ダイアログが開き、<tt>sample</tt>がサンプル・データベースの名前であることを通知し、このデータベースの表、オブジェクトおよびデータを作成するかどうかをユーザーに質問します。<br><img alt="データベースにサンプル・データを生成するためのプロンプト" class="margin-around" src="../../../images_www/articles/72/websvc/rest/create-sample-contents.png"> </li>
<li>「はい」をクリックします。IDEはデータベースを作成してデータを生成し、このデータベースに接続を追加します。<br><img alt="「サービス」ウィンドウの生成されたサンプル・データベースとデータベース接続" class="margin-around b-bottom" src="../../../images_www/articles/72/websvc/rest/generated-db.png"> </li>
</ol>
<h2><a name="create-services-from-db"></a>データベースからのRESTful Webサービスの作成 </h2>
<p>この課題の目標は、プロジェクトを作成し、データベースからエンティティ・クラスとRESTful Webサービスを生成することです。</p>
<p>この項ではJavaDB (Derby)データベースとjdbc/sampleデータ・ソースを使用します。JavaDBはSDKに含まれています。jdbc/sampleデータ・ソースは、IDEとGlassFishを一緒にインストールするとき、NetBeans IDEによって自動的に生成されます。</p>
<div class="indent">
<!-- =========================================== -->
<h3><a name="create-project"></a>プロジェクトの作成</h3>
<p>RESTful Webサービスを作成するには、Java Webアプリケーション・プロジェクトが必要です。 </p>
<p><strong>プロジェクトを作成するには:</strong></p>
<ol>
<li><p>「ファイル」>「新規プロジェクト」(LinuxおよびWindowsでは[Ctrl]-[Shift]-[N]、MacOSでは[⌘]-[Shift]-[N])を選択します。「カテゴリ」から「Java Web」を選択します。「プロジェクト」で「Webアプリケーション」を選択します。「次」をクリックします。新規Webアプリケーション・ウィザードが開きます。</p>
<p>あるいは、Maven Webアプリケーションも作成できます。「ファイル」>「新規プロジェクト」(LinuxおよびWindowsでは[Ctrl]-[Shift]-[N]、MacOSでは[⌘]-[Shift]-[N])を選択します。「カテゴリ」から「Maven」を選択します。「プロジェクト」で「Maven Webアプリケーション」を選択して、「次」をクリックします。 </p>
</li>
<li>「プロジェクト名」に「<tt>CustomerDB</tt>」と入力します。「次」をクリックします。</li>
<li>「Java EE 6 Web」または「Java EE 7 Web」を選択します。「サーバー」で使用するサーバーを選択しますが、Java EEプロジェクトには、GlassFishサーバー3.xまたは4.xが必要であることに注意してください。残りのオプションをクリックして進み、「終了」をクリックします。
<p class="alert"><b>Mavenプロジェクトで重要: </b>NetBeans IDE 7.2では、Maven Webアプリケーションを作成するときはサーバーを設定できません。ただし、永続性ユニットを作成するには、サーバーを設定する必要があります。したがって、Maven Webアプリケーションを作成した後、プロジェクトの「プロパティ」を開き、「実行」プロパティでサーバーを設定します。プロジェクトの「プロパティ」を開くには、プロジェクト・ノードを右クリックし、コンテキスト・メニューから「プロパティ」を選択します。</p>
</li>
</ol>
<!-- =========================================== -->
<h3><a name="entities-and-services"></a>エンティティ・クラスとRESTfulサービスの生成</h3>
<p>Java Webアプリケーションを準備した後、エンティティ・クラスとRESTful Webサービスをプロジェクトに追加します。</p>
<p><strong>エンティティ・クラスとRESTful Webサービスを生成するには:</strong></p>
<ol>
<li><tt>CustomerDB</tt>」ノードを右クリックし、「新規」>「その他」>「Webサービス」>「データベースからのRESTful Webサービス」を選択します。新規RESTful Webサービス・ウィザードの「データベース表」パネルが開きます。<br> <img alt="メニュー内の「データベースからのRESTful Webサービス」オプション" class="margin-around" src="../../../images_www/articles/72/websvc/rest/open-wizard.png"> </li>
<li>GlassFishサーバーを使用している場合は、「データベース表」パネルの「データ・ソース」ドロップダウン・フィールドから「<tt>jdbc/sample</tt>」データ・ソースを選択します。
<p>Tomcatを使用している場合は、「jdbc:derby://localhost:1527/sample」を選択します。Derbyデータベース・サーバーが自動的に起動しない場合は、「サービス」ウィンドウの「データベース」タブから起動する必要があります。</p>
<p class="notes"><b>MySQLユーザーへの注意:</b> 新規データ・ソースを作成する必要があります。「新規データ・ソース」を選択し、わかりやすい任意の名前を付け、「<tt>jdbc:mysql://localhost:3306/sample</tt>」データベース接続を選択します。この接続は、MySQL上にサンプル・データベースを作成したときに作成しました。<br><img alt="mysql接続を使用する新規データ・ソース" class="margin-around" src="../../../images_www/articles/72/websvc/rest/new-mysql-datasource.png"></p>
</li>
<li> 「使用可能な表」で「CUSTOMER」を選択し、「追加」をクリックします。CUSTOMERテーブルと関連のあるDISCOUNT_CODEテーブルが自動的に「選択した表」に追加されます。MySQLデータベースまたはDerbyの一部のバージョンを使用している場合は、MICRO_MARKET表も追加されます。次のようになります(Derbyバージョン)。<br> <br> <img alt="データベースからの新規エンティティ・クラス・ウィザードの「データベース表」パネルでCUSTOMERおよびDISCOUNT_CODE表が選択された状態" border="1" class="margin-around" src="../../../images_www/articles/72/websvc/rest/select-tables.png" title="データベースからの新規エンティティ・クラス・ウィザードの「データベース表」パネルでCUSTOMERおよびDISCOUNT_CODE表が選択された状態"></li>
<li>「次」をクリックします。エンティティ・クラス・ページが開きます。「パッケージ名」に「<tt>entities</tt>」と入力します。次のようになります(Derbyバージョン)。
<p class="notes"><b>注意:</b> データベースからのRESTful Webサービス・ウィザードはJAXB注釈を自動的に生成します。Java EEアプリケーションのエンティティ・クラスを、「データベースからのエンティティ・クラス」ウィザードで生成し、後でこれらのエンティティ・クラスからRESTful Webサービスを作成する可能性がある場合は、「JAXB注釈を生成」ボックスが選択されていることを確認します。また、エンティティ・クラスからのRESTful Webサービス・ウィザードを実行する前に、JAXB注釈をエンティティ・クラスに手作業で追加することもできます。詳細は、<a href="http://netbeans.dzone.com/nb-generate-simpler-rest" target="_blank">NetBeansによる簡易なRESTful Webサービスの生成</a>を参照してください。 </p>
<img alt="パッケージ名が表示された、「データベースからのRESTful Webサービス」ウィザードの「エンティティ・クラス」パネル" class="margin-around" src="../../../images_www/articles/71/websvc/rest/entity-classes.png"></li>
<li>「次」をクリックします。生成したサービス・クラスおよびパッケージの名前と場所を設定できるパネルが開きます。Java EEプロジェクトの場合、RESTアプリケーション構成クラスの名前と場所を変更できます。
<!-- <p class="alert"><strong>Spring framework applications:</strong> Register the RESTful resources in the <tt>web.xml</tt> deployment descriptor.
Do NOT use <tt>javax.ws.rs.core.Application</tt>.</p>-->
<p>このチュートリアルでは、デフォルトを受け入れて「終了」をクリックします。「終了」をクリックすると、IDEによってエンティティ・クラスとサービス・クラスが生成されます。Java EEプロジェクトでは、IDEによって、アプリケーションのサブクラスであるアプリケーション構成クラスも生成されます。</p>
<img alt="生成されたサービスとサービス構成のクラスおよびパッケージ" class="margin-around" src="../../../images_www/articles/72/websvc/rest/class-name-location.png">
</li>
</ol>
</div>
<p>IDEにより、RESTful Webサービスが生成されます。IDEが終了した後、「プロジェクト」ウィンドウを見ます。生成されたエンティティ・クラスは<tt>entities</tt>パッケージ内にあり、サービスは<tt>service</tt>内にあります。データベースからのJava EE RESTful Webサービスは、各サービス・クラスの<tt>EntityManager</tt>をインスタンス化します。これにより、JPAコントローラ・クラスが不要になり、より簡易なコードが生成されます。</p>
<!-- ===================================================================================== -->
<h2><a name="test-rest"></a>RESTful Webサービスのテスト</h2>
<p>この課題の目標は、アプリケーションを試してみることです。テスト用に新しいWebアプリケーションを作成し、IDEのウィザードを使用して新規プロジェクトにテストを生成します。</p>
<ol>
<li>メイン・メニューから「ファイル」>「新規プロジェクト」を選択します。</li>
<li>「Java Web」カテゴリで「Webアプリケーション」プロジェクト・タイプを選択します。「次」をクリックします。</li>
<li>プロジェクト名に<strong>「WebServicesTest」</strong>と入力します。「次」をクリックします。</li>
<li>ターゲット・サーバーとして「GlassFish Server」を選択し、Java EEバージョンとして「Java EE 6 Web」または「Java EE 7 Web」を選択します。「終了」をクリックします。</li>
<li><tt>CustomerDB</tt>プロジェクト・ノードを右クリックし、「RESTful Webサービスをテスト」を選択します。テスト・クライアントを生成する場所を、サービス・プロジェクト内にするか、別のJava Webプロジェクト内にするかを質問するダイアログが開きます。このオプションによって、一部のブラウザのセキュリティ制限を回避できます。CustomerDBプロジェクトと同じサーバー・ドメインにデプロイされるように構成されているかぎり、すべてのWebプロジェクトを使用できます。 <br><img alt="テスト・クライアントをローカルで生成するか、または同じドメインにデプロイされている別のJava Webプロジェクト内に生成するかを選択するためのダイアログ" class="margin-around" src="../../../images_www/articles/71/websvc/rest/configure-test-client.png"></li>
<li><strong>「プロジェクト内のWebテスト・クライアント」</strong>を選択し、「参照」をクリックします。</li>
<li>「プロジェクトを選択」ダイアログ・ボックスで「WebServiceTest」プロジェクトを選択します。「OK」をクリックします。
<p>IDEによって、<tt>test-resbeans.html</tt>ファイルがWebServiceTestプロジェクトに生成されます。IDEによってサーバーの起動およびCustomerDBアプリケーションのデプロイも自動的に行われます。 </p>
<p class="notes">1つ以上のクラスが存在しておらず、プロジェクトがビルドされないというエラー・メッセージが「出力」ウィンドウに表示された場合、コンパイル時ライブラリにJerseyライブラリを追加します。プロジェクトのノードを右クリックし、「プロパティ」を選択します。「プロパティ」ツリー・メニューで、「ライブラリ」を選択します。「ライブラリの追加」をクリックし、Jerseyライブラリを参照します。</p>
</li>
<li>WebServiceTestを右クリックし、「実行」を選択します。</li>
<li>ブラウザで<a href="http://localhost:8080/WebServicesTest/test-resbeans.html">http://localhost:8080/WebServicesTest/test-resbeans.html</a>を開きます。<br> <img alt="ブラウザでのRESTful Webサービス・テスターの開始ページ" border="1" class="margin-around" src="../../../images_www/articles/71/websvc/rest/test-rest1.png" title="ブラウザでのRESTful Webサービス・テスターの開始ページ">
<p>左側にルート・リソースの組があります。ここでは、<tt>entities.customer</tt><tt>entities.discountCodes</tt>および<tt>entities.microMarket</tt>という名前です。</p>
</li>
<li><tt>entities.customer</tt>」ノードをクリックします。「テストするメソッドを選択します」フィールドで、「GET (application/json)」または「GET (application/xml)」を選択します。「テスト」をクリックします。テスト・クライアントによってリクエストが送信され、「テスト出力」セクションに結果が表示されます。テスト・クライアントでは、デフォルトで「rawデータのビュー」が表示されます。次のイメージは、application/xmlリクエストに対するレスポンスを示しています。<br> <img alt="RESTful Webサービス・テスターの「rawデータのビュー」ウィンドウ" class="margin-around" src="../../../images_www/articles/72/websvc/rest/test-rest-raw.png"></li>
</ol>
<p>「テスト出力」セクションには5つのタブがあります。 </p>
<ul>
<li>「表形式ビュー」は、結果のドキュメントにあるすべてのURIを表示するフラットなビューです。現在このビューには、コンテナ-被コンテナ関係が許可されていないという警告のみが表示されます。</li>
<li>「rawデータのビュー」は実際に返ってきたデータを表示します。選択したMIMEタイプ(<tt>application/xml</tt>または<tt>application/json</tt>)により、表示されるデータはそれぞれXMLまたはJSON形式です。 </li>
<li>「サブリソース」タブには、ルート・リソースとサブリソースのURLが表示されます。RESTful Webサービスはデータベースのエンティティ・クラスに基づいており、ルート・リソースはデータベース表を、サブリソースは列を表します。</li>
<li>「ヘッダー」タブにはHTTPヘッダー情報が表示されます。 </li>
<li>「HTTPモニター」タブに、送受信された実際のHTTPリクエストおよびレスポンスが表示されます。 </li>
</ul>
<p>ブラウザを閉じ、IDEに戻ります。</p>
<!-- ===================================================================================== -->
<!--
<h2><a name="add-google-map"></a>
Adding a Google Map Feature</h2>
<p>The goal of this exercise is to add Google map
functionality to our RESTful web services.</p>
<ol>
<li>Open the <tt>CustomerRESTFacade</tt> class (EE 5) or <tt>CustomerFacadeREST</tt> class (EE 6)
in the editor. </li>
<li><a name="add_method_step"></a>Add the following method to the class:
<pre>@GET
@Produces("text/html")
public String getGoogleMap() {
// Drag and drop the getGoogleMap operation here
return "";
}</pre>
</li>
<li><a name="get_google_map_key"></a>Sign up for a Google map key at <a target="_blank" href="http://www.google.com/apis/maps/signup.html">http://www.google.com/apis/maps/signup.html</a>. The Google map key request dialog has a field for your website's URL. Type <tt>http://localhost:8080</tt> in that field.</li>
<li>In the IDE, open the Services tab and expand the Web Services node. Under Web Services, expand Google. Under Google, expand Map Service.<br>
<br><img class="margin-around" alt="services view showing google map service" title="Services view showing Google map service" src="../../../images_www/articles/71/websvc/rest/google-saas.png"></li>
<li>Drag the getGoogleMap item and drop it into the body of the <tt>getGoogleMap</tt> method you created in <a href="#add_method_step">Step 2</a>, just before the <tt>return = &quot;&quot;;</tt> line. The Customize getGoogleMap SAAS dialog opens. Accept the defaults and click OK.
<p>The IDE adds the following <tt>try</tt> block to the <tt>getGoogleMap</tt> method.
<pre>@GET
@Produces("text/html")
public String getGoogleMap() {
// Drag and drop the getGoogleMap operation here
try {
String address = "16 Network Circle, Menlo Park";
java.lang.Integer zoom = 15;
String iframe = "false";
RestResponse result = GoogleMapService.getGoogleMap(address, zoom, iframe);
//TODO - Uncomment the print Statement below to print result.
//System.out.println("The SaasService returned: "+result.getDataAsString());
} catch (Exception ex) {
ex.printStackTrace();
}
return "";
}
</pre>
<p>The IDE also creates the packages org.netbeans.saas and org.netbeans.saas.google, which contain the following classes and resources: </p>
<ul>
<li><tt>RestConnection</tt> - A wrapper around HttpUrlConnection </li>
<li><tt>RestResponse</tt> - A wrapper for the HTTP response</li>
<li><tt>googlemapservice.properties</tt> - A properties file that stores the API key </li>
<li><tt>GoogleMapService</tt> - A service wrapper containing the wrapper methods that uses RestConnection to make calls to the Google Map service.</li>
</ul>
<img src="../../../images_www/articles/71/websvc/rest/project-w-google-ee6.png" alt="Projects window showing packages added after get Google Map method is dropped into Customer Resource" class="margin-around">
<li>In the try block of getGoogleMap(), replace the commented-out print statement with the line <span class="examplecode"><tt>return result.getDataAsString();</tt></span>. The method now looks like this:
<pre>@GET
@Produces("text/html")
public String getGoogleMap() {
// Drag and drop the getGoogleMap operation here
try {
String address = "16 Network Circle, Menlo Park";
java.lang.Integer zoom = 15;
String iframe = "false";
RestResponse result = GoogleMapService.getGoogleMap(address, zoom, iframe);
return result.getDataAsString();
} catch (Exception ex) {
ex.printStackTrace();
}
return "";
}</pre>
</li>
<li>Open <tt>googlemapservice.properties</tt>. Paste in the API key you got from Google in <a href="#get_google_map_key">Step 3</a>.
Save your changes. The IDE automatically redeploys your project.
<li>Refresh your browser window with the test client. </li>
<li>Click <tt>entities.customer</tt> in the left sidebar. The <code>GET (text/html)</code> method appears in the &quot;Choose method to test&quot; field. Click Test. The GoogleMap of 16 Network Circle, Menlo Park opens in the Raw View.
<br>
<img src="../../../images_www/articles/71/websvc/rest/menlo-park-map.png" alt="RESTful services test page showing Google map of Menlo Park" border="1" class="margin-around"> </li>
<li>
<p>The Google map of the Menlo Park address appears for all customers in the database. To display the Google maps of the actual addresses of the customers, create an instance of Customer and set the address equal to a concatenation of address variables for that instance of Customer. </p>
<p>Find an instance of Customer by calling the entity manager's <tt>find()</tt> method. In an EE5 service, the customer facade uses its own <code>find</code> method to call <code>CustomerJpaController</code>, which instantiates the entity manager. In an EE6 service, the customer facade uses the abstract facade to access the entity manager. The generic <tt>find()</tt> method requires explicit argument type casting to Object and an explicit entity id. The following code displays the map location of the customer with id number 1 (changes in bold):</p>
<p><b>EE5 service:</b></p>
<pre>@GET
@Produces("text/html")
public String getGoogleMap() {
try {
<b>Customer c = find(1);
String address = c.getAddressline1() + " " + c.getAddressline2() + " " +
c.getCity() + " " + c.getState() + " " + c.getZip();</b>
java.lang.Integer zoom = 15;
String iframe = "false";
RestResponse result = GoogleMapService.getGoogleMap(address, zoom, iframe);
return result.getDataAsString();
} catch (Exception ex) {
ex.printStackTrace();
}
<b></b>
return &quot;&quot;;
}</pre>
<p><b>EE6 service:</b></p>
<pre>@GET
@Produces("text/html")
public String getGoogleMap() {
try {
<b>Customer c = getEntityManager().find(Customer.class, 1);
String address = c.getAddressline1() + " " + c.getAddressline2() + " " +
c.getCity() + " " + c.getState() + " " + c.getZip();</b>
java.lang.Integer zoom = 15;
String iframe = "false";
RestResponse result = GoogleMapService.getGoogleMap(address, zoom, iframe);
return result.getDataAsString();
} catch (Exception ex) {
ex.printStackTrace();
}
<b></b>
return &quot;&quot;;
}</pre>
</li>
<li>Test the RESTful web services again. The customer id is specified as an argument for the <tt>find()</tt> method and the tester displays the raw view by default. For customer 1, the following map displays:
<p class="tips"><strong>Tip: </strong>Try to change the id number passed as an argument to <code>getEntityManager().find(Customer.class, id)</code>. A real world client would get the value of this argument from a UI form.</p>
<br><img border="1" src="../../../images_www/articles/70/websvc/rest/google-map-4.png" class="margin-around" alt="Google Map showing address of customer in database" title="Google Map showing address of customer in database">
<p class="notes"><b>Note: </b>If GoogleMaps cannot find an address, it shows a zoomed in view of the ocean.</p></li>
</ol>
-->
<!-- Spring Framework -->
<!-- <h2><a name="rest-spring"></a>RESTful Web Services in the Spring Framework</h2>
<p>Jersey is integrated into the Spring Framework. When you create a Java Web application with the Spring framework, a REST-aware servlet is automatically created. However, Spring 3 doesn't contain aopalliance.jar, which the RESTful web service requires to inject an EntityManager object.</p>
<div class="indent">
<h3><a name="create-spring-webapp"></a>Creating a Java Web Application With the Spring Framework</h3>
<p>When you create the Java Web application in the New Project wizard as described in <a href="#Exercise_1">Generating Entity Classes from a Database</a>, after you select the server, click Next instead of Finish
to open the Frameworks panel of the wizard. Select Spring Web MVC, then click Finish. </p>
<p class="notes"><strong>Note.</strong> If you already created your project you can add support for the
Spring Web MVC framework by right-clicking the project node in the Projects
window and choosing Properties in the popup menu.
In the Project Properties window, select the Frameworks category and then click Add and select
Spring Web MVC.</p>
<h3><a name="add-aopalliance"></a>Adding aopalliance.jar to the Project</h3>
<p>Spring 3 does not contain <tt>aopalliance.jar</tt>. The application requires this library to inject EntityManager. To fix the problem you need to download this jar and add it to your classpath. See <a href="https://netbeans.org/bugzilla/show_bug.cgi?id=193626" title="https://netbeans.org/bugzilla/show_bug.cgi?id=193626">Issue 193626</a> and the <a target="_blank" href="http://forum.springsource.org/showthread.php?t=10511" title="http://forum.springsource.org/showthread.php?t=10511">Spring forums</a>. </p>
<p><strong>To add aopalliance.jar:</strong></p>
<ol>
<li>Download a zip archive of <tt>aopalliance.jar</tt> from <a target="_blank" href="http://sourceforge.net/projects/aopalliance/files/aopalliance/1.0/" title="http://sourceforge.net/projects/aopalliance/files/aopalliance/1.0/" rel="nofollow">http://sourceforge.net/projects/aopalliance/files/aopalliance/1.0/</a>.</li>
<li>Unzip the archive to the location of your choice.</li>
<li>Right-click your Spring RESTful Web Service project node in the Projects window and
choose Properties in the popup men and then select the Libraries category in the Project Properties window.<br>
<img src="../../../images_www/articles/72/websvc/rest/properties-node.png" height="537" width="340" alt="Context menu showing properties node" class="margin-around">
<p>Alternatively, you can right-click the Libraries node of the project in the
Projects window and choose Add JAR/Folder.</p></li>
<li>Click Add JAR/Folder and locate the <tt>aopalliance.jar</tt> in the file system browser. Click Open.
<p>You will want to use the absolute path reference.</p>
<img src="../../../images_www/articles/72/websvc/rest/browse-for-aopalliance.png" alt="Browsing for aopalliance.jar" height="404" width="586" class="margin-around"></li>
<li>The <tt>aopalliance.jar</tt> file is now included in your libraries. Click OK. <br>
<img src="../../../images_www/articles/72/websvc/rest/libraries.png" alt="Library properties showing added aopalliance.jar" height="461" width="600" class="margin-around"> </li>
</ol>
<h3><a name="create-spring-restful-services"></a>Creating RESTful Services in the Spring-enabled Project</h3>
<p>After you create a Java web application with the Spring framework and add <tt>aopalliance.jar</tt>
to the project's classpath, run the RESTful Web Service from Database wizard as described in <a href="#entities-and-services">Generating Entities and Services</a>. However, do NOT register RESTful resources with a subclass of <tt>javax.ws.rs.core.Application</tt>. Instead use the <tt>web.xml</tt> deployment descriptor. The Spring framework generates a <tt>web.xml</tt> deployment descriptor in all cases.</p>
<img src="../../../images_www/articles/72/websvc/rest/ee6-rest-configuration.png" alt="Options for registering RESTful resources, web.xml chosen" height="319" width="486" class="margin-around">
<p>For more about the features of Spring framework projects in NetBeans IDE, see <a href="../../docs/web/quickstart-webapps-spring.html">Introduction to the Spring Framework</a>.</p>
<h3><a name="spring-errors"></a>Compilation Errors</h3>
<p>You might have compilation errors in the generated service classes. You see these errors if you create the RESTful services before you add <tt>aopalliance.jar</tt> to the classpath. </p>
<p><strong>To fix compilation errors in service classes:</strong></p>
<ol>
<li>Make certain that you add <tt>aopalliance.jar</tt> to the classpath, as described in <a href="#add-aopalliance">Adding aopalliance.jar to the Project</a>.</li>
<li>In the IDE's top menu bar, click Edit and select Find in Projects...</li>
<li>Search for all occurrences of the <tt>@Error</tt> annotation in the project.<br>
<img src="../../../images_www/articles/72/websvc/rest/find-error.png" alt="Find in Projects dialog showing search for the @Error annotation" height="307" width="431" class="margin-around"></li>
<li>Delete every <tt>@Error</tt> line from the code.<br>
<img src="../../../images_www/articles/72/websvc/rest/error-lines.png" alt="Search results for @Error, with one line highlighted and about to be deleted" height="558" width="590" class="margin-around"></li>
</ol>
</div>-->
<div class="feedback-box" ><a href="/about/contact_form.html?to=3&amp;subject=Feedback:%20Getting%20Started%20with%20REST%20Services%20in%20NetBeans%20IDE%20">このチュートリアルに関するご意見をお寄せください</a></div>
<br style="clear:both;">
<h2><a name="seealso"></a>関連項目</h2>
<p>NetBeans IDEを使用したJava EEアプリケーションの開発方法の詳細は、次のリソースを参照してください。
</p>
<ul>
<li><a href="http://netbeans.dzone.com/nb-generate-simpler-rest" target="_blank">NetBeansによる簡易なRESTful Webサービスの生成</a></li>
<li><a href="../../trails/web.html">Webサービスの学習</a></li>
<li>YouTube: <a href="http://www.youtube.com/watch?v=cDdfVMro99s" target="_blank" title="RESTful Web Services, Building and Deploying (Part 1)">RESTful Web Services, Building and Deploying (Part 1)</a></li>
<li>YouTube: <a href="http://www.youtube.com/watch?v=_c-CCVy4_Eo" target="_blank" title="NetBeans RESTful Testing and Invoking RESTful Resources (Part 2)">NetBeans RESTful Testing and Invoking RESTful Resources (Part 2)</a></li>
</ul>
<p><a href="../../../community/lists/top.html">nbj2ee@netbeans.orgメーリング・リスト</a>に登録することによって、NetBeans IDE Java EE開発機能に関するご意見やご提案を送信したり、サポートを受けたり、最新の開発情報を入手したりできます。</p>
</body>