Restful-methods
RESTful Webサービス-メソッド
これまでに説明したように、RESTful WebサービスはHTTP動詞を頻繁に使用して、指定されたリソースで実行される操作を決定します。 次の表に、HTTP動詞の一般的な使用例を示します。
HTTP Method | GET |
URI | http://localhost:8080/UserManagement/rest/UserService/users |
Operation | Get list of users |
Operation Type | Read Only |
HTTP Method | GET |
URI | http://localhost:8080/UserManagement/rest/UserService/users/1 |
Operation | Get user of Id 1 |
Operation Type | Read Only |
HTTP Method | POST |
URI | http://localhost:8080/UserManagement/rest/UserService/users/2 |
Operation | Insert user with Id 2 |
Operation Type | Non-Idempotent |
HTTP Method | PUT |
URI | http://localhost:8080/UserManagement/rest/UserService/users/2 |
Operation | Update User with Id 2 |
Operation Type | N/A |
HTTP Method | DELETE |
URI | http://localhost:8080/UserManagement/rest/UserService/users/1 |
Operation | Delete User with Id 1 |
Operation Type | Idempotent |
HTTP Method | OPTIONS |
URI | http://localhost:8080/UserManagement/rest/UserService/users |
Operation | List the supported operations in web service |
Operation Type | Read Only |
HTTP Method | HEAD |
URI | http://localhost:8080/UserManagement/rest/UserService/users |
Operation | Returns only HTTP Header, no Body |
Operation Type | Read Only |
考慮すべき重要な点は次のとおりです。
- GET操作は読み取り専用で安全です。
- PUTおよびDELETE操作はi等です。これらの操作が何度呼び出されても、結果は常に同じです。
- PUT操作とPOST操作はほぼ同じですが、PUT操作がi等で、POST操作が異なる結果を引き起こす可能性のある結果にのみ違いがあります。
例
link:/restful/restful_first_application [RESTful Web Services-First Application]チュートリアルで作成したサンプルを更新して、CRUD(作成、読み取り、更新、削除)操作を実行できるWebサービスを作成してみましょう。 簡単にするために、ファイル操作を使用してデータベース操作を置き換えました。
com.finddevguidesパッケージの下にある UserService.java 、 User.java 、 UserDao.java ファイルを更新します。
User.java
UserDao.java
UserService.java
Eclipseを使用して、アプリケーションをwarファイルとしてエクスポートし、同じものをtomcatにデプロイします。 Eclipseを使用してWARファイルを作成するには、 File→ export→ Web> War File オプションに従って、最後にプロジェクトUserManagementと宛先フォルダーを選択します。 Tomcatにwarファイルをデプロイするには、* Tomcatインストールディレクトリ*> webappsディレクトリにUserManagement.warを配置し、Tomcatを起動します。
Webサービスのテスト
Jerseyは、WebサービスをテストするWebサービスクライアントを作成するAPIを提供します。 同じプロジェクトのcom.finddevguidesパッケージの下にサンプルテストクラス WebServiceTester.java を作成しました。
WebServiceTester.java
次に、Eclipseを使用してテスターを実行します。 ファイルを右クリックし、[として実行→ Javaアプリケーション]オプションに従います。 Eclipseコンソールに次の結果が表示されます。
link:/cgi-bin/printpage.cgi [__印刷]