JAX-RSとJerseyを使用してJavaでRESTfulサービスを構築する(摂氏から華氏および華氏から摂氏)
公開: 2020-03-25
以下の質問/質問のいずれかがありますか?
- 華氏を摂氏に、摂氏を華氏に変換するJavaRESTサービスを作成します
- ジャージーを使用したJavaによるREST(JAX-RS)
- Javaでの華氏から摂氏法への変換
- 度の変換を伴う宿題のヘルプ(CtoF、FtoC)
- RESTfulWebサービス用のJavaAPI
- Webサービス–最高のJava REST APIはどれですか?
- Java用のRESTAPI?
- ctofおよびftocチュートリアル。 ctofおよびftocJavaチュートリアル
- Javaテクノロジを使用してRESTfulWebサービスを作成する
- Java用のRESTfulWebAPIフレームワーク
RESTful Service
:Representational State Transfer(REST)は、SOAPおよびWebサービス記述言語(WSDL)ベースのWebサービスのより単純な代替手段として、Web全体で広く受け入れられています。
RESTは、さまざまな言語で記述されたさまざまなクライアントがリソースの状態をHTTP経由でアドレス指定および転送する方法など、システムのリソースに焦点を当てたWebサービスを設計するための一連のアーキテクチャー原則を定義します。 それを使用するWebサービスの数で測定すると、RESTはここ数年だけで主要なWebサービス設計モデルとして登場しました。 実際、RESTはWebに非常に大きな影響を与えたため、SOAPベースおよびWSDLベースのインターフェイス設計は、使用するのがかなり単純なスタイルであるため、ほとんど置き換えられました。
RESTFulとSOAPチュートリアル。

JAX-RS:
RESTfulWebサービス用のJavaAPI(JAX-RS)は、開発者RESTサービスへのAPIの場合に設定されます。 JAX-RSはJavaEE6の一部であり、開発者がRESTWebアプリケーションを簡単に開発できるようにします。
ジャージー:
ジャージーは、RESTful Webサービスを構築するためのオープンソース、本番品質、JAX-RS(JSR 311)リファレンス実装です。 しかし、それはリファレンス実装以上のものでもあります。 JerseyはAPIを提供しているため、開発者はニーズに合わせてJerseyを拡張できます。
以下の手順で簡単なRESTful API
の構築を始めましょう。
ステップ1
Eclipseの場合=>ファイル=>新規=>動的Webプロジェクト。 「 CrunchifyRESTJerseyExample
」という名前を付けます。

必ず設定してください:
- ターゲットランタイム:Apache Tomcat v9.0
- 動的Webモジュールのバージョン:4.0
ステップ2
web.xml
(デプロイメント記述子)が表示されない場合は、次の手順に従ってください。 また
- プロジェクトを右クリック
Java EE Tools
選択します- [
Generate Deployment Descriptor Stub
クリックします
これにより、 /WebContent/WEB-INF/
フォルダーの下にweb.xml
ファイルが作成されます。
ステップ-3
次に、ProjectをMaven Project
に変換して、必要な.jarファイルを依存関係として追加できるようにします。
手順:
- プロジェクトを右クリック
- [
Configure
]をクリックします - [
Convert to Maven Project
]オプションを選択します。


変更を加えずに[ Finish button
をクリックするだけです。

ステップ-4
pom.xml
ファイルを開き、以下の依存関係を追加します。
- asm.jar
- jersey-bundle.jar
- json.jar
- jersey-server.jar

これが私のpom.xml
ファイルです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
< project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns : xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi : schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > < modelVersion > 4.0.0 < / modelVersion > < groupId > CrunchifyRESTJerseyExample < / groupId > < artifactId > CrunchifyRESTJerseyExample < / artifactId > < version > 0.0.1 - SNAPSHOT < / version > < packaging > war < / packaging > < build > < sourceDirectory > src < / sourceDirectory > < plugins > < plugin > < artifactId > maven - compiler - plugin < / artifactId > < version > 3.7.0 < / version > < configuration > < source > 1.7 < / source > < target > 1.7 < / target > < / configuration > < / plugin > < / plugins > < / build > < dependencies > < dependency > < groupId > asm < / groupId > < artifactId > asm < / artifactId > < version > 3.3.1 < / version > < / dependency > < dependency > < groupId > com . sun . jersey < / groupId > < artifactId > jersey - bundle < / artifactId > < version > 1.19.4 < / version > < / dependency > < dependency > < groupId > org . json < / groupId > < artifactId > json < / artifactId > < version > 20170516 < / version > < / dependency > < dependency > < groupId > com . sun . jersey < / groupId > < artifactId > jersey - server < / artifactId > < version > 1.19.4 < / version > < / dependency > < dependency > < groupId > com . sun . jersey < / groupId > < artifactId > jersey - core < / artifactId > < version > 1.19.4 < / version > < / dependency > < / dependencies > < / project > |
ステップ-5
これでweb.xmlファイルを更新します。 これが私のweb.xml
ファイルのコピーです:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<? xml version = "1.0" encoding = "UTF-8" ?> < web - app xmlns : xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns : web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi : schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version = "3.0" > < display - name > CrunchifyRESTJerseyExample < / display - name > < welcome - file - list > < welcome - file > index . html < / welcome - file > < welcome - file > index . htm < / welcome - file > < welcome - file > index . jsp < / welcome - file > < welcome - file > default . html < / welcome - file > < welcome - file > default . htm < / welcome - file > < welcome - file > default . jsp < / welcome - file > < / welcome - file - list > < servlet > < servlet - name > Jersey Web Application < / servlet - name > < servlet - class > com . sun . jersey . spi . container . servlet . ServletContainer < / servlet - class > < load - on - startup > 1 < / load - on - startup > < / servlet > < servlet - mapping > < servlet - name > Jersey Web Application < / servlet - name > < url - pattern > / crunchify /* < / url - pattern > < / servlet - mapping > < / web - app > |
ステップ-6
-
Java Resources
に移動 - srcをクリックします
- 右クリック->新規->クラス
- パッケージ:com.crunchify.restjersey
- 名前:CtoFService
CtoFService.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
package com . crunchify . restjersey ; /** * @author Crunchify.com * * Description: This program converts unit from Centigrade to Fahrenheit. * Last updated: 12/28/2018 */ import javax . ws . rs . GET ; import javax . ws . rs . Path ; import javax . ws . rs . PathParam ; import javax . ws . rs . Produces ; @ Path ( "/ctofservice" ) public class CtoFService { @ GET @ Produces ( "application/xml" ) public String convertCtoF ( ) { Double fahrenheit ; Double celsius = 36.8 ; fahrenheit = ( ( celsius * 9 ) / 5 ) + 32 ; String result = "@Produces(\"application/xml\") Output: \n\nC to F Converter Output: \n\n" + fahrenheit ; return "<ctofservice>" + "<celsius>" + celsius + "</celsius>" + "<ctofoutput>" + result + "</ctofoutput>" + "</ctofservice>" ; } @ Path ( "{c}" ) @ GET @ Produces ( "application/xml" ) public String convertCtoFfromInput ( @ PathParam ( "c" ) Double c ) { Double fahrenheit ; Double celsius = c ; fahrenheit = ( ( celsius * 9 ) / 5 ) + 32 ; String result = "@Produces(\"application/xml\") Output: \n\nC to F Converter Output: \n\n" + fahrenheit ; return "<ctofservice>" + "<celsius>" + celsius + "</celsius>" + "<ctofoutput>" + result + "</ctofoutput>" + "</ctofservice>" ; } } |
ステップ-7
同じ方法でFtoCService.javaを作成します
FtoCService.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
package com . crunchify . restjersey ; /** * @author Crunchify, LLC * Description: This program converts unit from Fahrenheit to Centigrade. * */ import javax . ws . rs . GET ; import javax . ws . rs . Path ; import javax . ws . rs . PathParam ; import javax . ws . rs . Produces ; import javax . ws . rs . core . Response ; import org . json . JSONException ; import org . json . JSONObject ; @ Path ( "/ftocservice" ) public class FtoCService { @ GET @ Produces ( "application/json" ) public Response convertFtoC ( ) throws JSONException { JSONObject jsonObject = new JSONObject ( ) ; Double fahrenheit = 98.24 ; Double celsius ; celsius = ( fahrenheit - 32 ) * 5 / 9 ; jsonObject . put ( "F Value" , fahrenheit ) ; jsonObject . put ( "C Value" , celsius ) ; String result = "@Produces(\"application/json\") Output: \n\nF to C Converter Output: \n\n" + jsonObject ; return Response . status ( 200 ) . entity ( result ) . build ( ) ; } @ Path ( "{f}" ) @ GET @ Produces ( "application/json" ) public Response convertFtoCfromInput ( @ PathParam ( "f" ) float f ) throws JSONException { JSONObject jsonObject = new JSONObject ( ) ; float celsius ; celsius = ( f - 32 ) * 5 / 9 ; jsonObject . put ( "F Value" , f ) ; jsonObject . put ( "C Value" , celsius ) ; String result = "@Produces(\"application/json\") Output: \n\nF to C Converter Output: \n\n" + jsonObject ; return Response . status ( 200 ) . entity ( result ) . build ( ) ; } } |
ステップ-8
それでは、Eclipseワークスペースをクリーンアップしてプロジェクトをビルドしましょう。

1 2 3 |
1. Project - > Clean 2. Project - > Right click - > Maven - > Update Project 3. Project - > Right click - > Run As . . - > Maven Build ( option 5 ) - > Add "clean install" - > Run |
- 上記の
point 3
についてはthese screenshots
を使用してください:Mavenビルド、クリーンインストール。 - ビルド成功メッセージが表示されます。
ステップ-9
プロジェクトCrunchifyRESTJerseyExample
をTomcatにデプロイします。 まだ行っていない場合は、EclipseでTomcatをセットアップする方法の詳細な手順を次に示します。
- [サーバー]タブに移動します
- サーバーを右クリック
- [
Add and Remove Projects
クリックします - 左側からプロジェクトを選択し、[
Add
]をクリックします - [完了]をクリックします

ステップ-10
- Tomcat Server9.0を起動します

完全なプロジェクト構造:

Javaビルドパスの依存関係は次のとおりです。

このプロジェクトには必ずJDK1.8を使用してください。 Java 9以降– JAXB、JAX-WS、JAF、JTA、CORBAモジュールが削除され、これらのモジュールをMavenpom.xmlファイルに手動で追加する必要があります。
準備完了。
それでは、RESTfulWebサービスをテストしてみましょう。
テスト1:パラメータwithout
の摂氏から華氏へのWebサービス
リンク: http:// localhost:8080 / CrunchifyRESTJerseyExample / crunchify / ctofservice /

テスト2:パラメータを使用with
た摂氏から華氏へのWebサービス

テスト3:パラメータwithout
の華氏から摂氏のWebサービス

テスト4:パラメータを使用with
た華氏から摂氏へのWebサービス

RESTFulクライアントの例:
- ApacheHttpClientを使用してRESTfulJavaクライアントを作成する方法–例
- Java.Net.URLを使用してRESTfulJavaクライアントを作成する方法–例
- Jerseyクライアントを使用してRESTfulJavaクライアントを作成する方法–例
別の人は読む必要があります:
- CrunchifyJSONtoHTML.js –JSONからHTMLへのテーブルコンバータスクリプト
- プログラムでJavaでメモリ不足(OOM)を生成する方法
- 1台のサーバーで複数のTomcatインスタンスを実行する方法は?
- JavaでファイルからJSONオブジェクトを読み取る方法–Crunchifyチュートリアル
コードの実行に問題がありますか?
いくつかのトリアージ手順:
最初は、 jersey-core
依存関係を使用していました。 ただし、以下の問題を回避するために、 jersey-server
依存関係も追加しました。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
SEVERE : Servlet [ Jersey Web Application ] in web application [ / CrunchifyRESTJerseyExample ] threw load ( ) exception java . lang . ClassNotFoundException : com . sun . jersey . spi . container . servlet . ServletContainer at org . apache . catalina . loader . WebappClassLoaderBase . loadClass ( WebappClassLoaderBase . java : 1328 ) at org . apache . catalina . loader . WebappClassLoaderBase . loadClass ( WebappClassLoaderBase . java : 1157 ) at org . apache . catalina . core . DefaultInstanceManager . loadClass ( DefaultInstanceManager . java : 542 ) at org . apache . catalina . core . DefaultInstanceManager . loadClassMaybePrivileged ( DefaultInstanceManager . java : 523 ) at org . apache . catalina . core . DefaultInstanceManager . newInstance ( DefaultInstanceManager . java : 150 ) at org . apache . catalina . core . StandardWrapper . loadServlet ( StandardWrapper . java : 1032 ) at org . apache . catalina . core . StandardWrapper . load ( StandardWrapper . java : 971 ) at org . apache . catalina . core . StandardContext . loadOnStartup ( StandardContext . java : 4829 ) at org . apache . catalina . core . StandardContext . startInternal ( StandardContext . java : 5143 ) at org . apache . catalina . util . LifecycleBase . start ( LifecycleBase . java : 183 ) at org . apache . catalina . core . ContainerBase $ StartChild . call ( ContainerBase . java : 1432 ) at org . apache . catalina . core . ContainerBase $ StartChild . call ( ContainerBase . java : 1422 ) at java . base / java . util . concurrent . FutureTask . run ( FutureTask . java : 264 ) at org . apache . tomcat . util . threads . InlineExecutorService . execute ( InlineExecutorService . java : 75 ) at java . base / java . util . concurrent . AbstractExecutorService . submit ( AbstractExecutorService . java : 140 ) at org . apache . catalina . core . ContainerBase . startInternal ( ContainerBase . java : 944 ) at org . apache . catalina . core . StandardHost . startInternal ( StandardHost . java : 831 ) at org . apache . catalina . util . LifecycleBase . start ( LifecycleBase . java : 183 ) at org . apache . catalina . core . ContainerBase $ StartChild . call ( ContainerBase . java : 1432 ) at org . apache . catalina . core . ContainerBase $ StartChild . call ( ContainerBase . java : 1422 ) at java . base / java . util . concurrent . FutureTask . run ( FutureTask . java : 264 ) at org . apache . tomcat . util . threads . InlineExecutorService . execute ( InlineExecutorService . java : 75 ) at java . base / java . util . concurrent . AbstractExecutorService . submit ( AbstractExecutorService . java : 140 ) at org . apache . catalina . core . ContainerBase . startInternal ( ContainerBase . java : 944 ) at org . apache . catalina . core . StandardEngine . startInternal ( StandardEngine . java : 261 ) at org . apache . catalina . util . LifecycleBase . start ( LifecycleBase . java : 183 ) at org . apache . catalina . core . StandardService . startInternal ( StandardService . java : 422 ) at org . apache . catalina . util . LifecycleBase . start ( LifecycleBase . java : 183 ) at org . apache . catalina . core . StandardServer . startInternal ( StandardServer . java : 801 ) at org . apache . catalina . util . LifecycleBase . start ( LifecycleBase . java : 183 ) at org . apache . catalina . startup . Catalina . start ( Catalina . java : 695 ) at java . base / jdk . internal . reflect . NativeMethodAccessorImpl . invoke0 ( Native Method ) at java . base / jdk . internal . reflect . NativeMethodAccessorImpl . invoke ( NativeMethodAccessorImpl . java : 62 ) at java . base / jdk . internal . reflect . DelegatingMethodAccessorImpl . invoke ( DelegatingMethodAccessorImpl . java : 43 ) at java . base / java . lang . reflect . Method . invoke ( Method . java : 566 ) at org . apache . catalina . startup . Bootstrap . start ( Bootstrap . java : 350 ) at org . apache . catalina . startup . Bootstrap . main ( Bootstrap . java : 492 ) |
上記のエラーが発生した場合は、pom.xmlファイルに以下のMaven依存関係を追加してみてください
1 2 3 4 5 |
< dependency > < groupId > org . glassfish . jersey . core < / groupId > < artifactId > jersey - server < / artifactId > < version > 2.27 < / version > < / dependency > |