使用 JAX-RS 和 Jersey 在 Java 中構建 RESTful 服務(攝氏到華氏和華氏到攝氏)
已發表: 2020-03-25
您是否有以下查詢/問題之一?
- 編寫一個 java REST 服務,將華氏溫度轉換為攝氏溫度,將攝氏度轉換為華氏溫度
- REST with Java (JAX-RS) 使用 Jersey
- Java中從華氏溫度到攝氏溫度的轉換
- 帶學位轉換的家庭作業幫助(CtoF,FtoC)
- 用於 RESTful Web 服務的 Java API
- Web 服務——哪個是最好的 Java REST API?
- Java的REST API?
- ctof 和 ftoc 教程。 ctof 和 ftoc Java 教程
- 使用 Java 技術創建 RESTful Web 服務
- 用於 Java 的 RESTful Web API 框架
RESTful Service
:具象狀態傳輸 (REST) 作為 SOAP 和基於 Web 服務描述語言 (WSDL) 的 Web 服務的更簡單替代方案,已在 Web 上獲得廣泛認可。
REST 定義了一組體系結構原則,您可以通過這些原則設計專注於系統資源的 Web 服務,包括各種用不同語言編寫的客戶端如何通過 HTTP 處理和傳輸資源狀態。 如果以使用它的 Web 服務的數量來衡量,REST 僅在最近幾年就已經成為一種主要的 Web 服務設計模型。 事實上,REST 已經對 Web 產生瞭如此大的影響,它主要取代了基於 SOAP 和 WSDL 的界面設計,因為它使用起來相當簡單。
RESTFul 對比SOAP 教程。

JAX-RS:
Java API for RESTful Web Services (JAX-RS),是一組用於開發人員 REST 服務的 API。 JAX-RS 是 Java EE6 的一部分,使開發人員能夠輕鬆開發 REST Web 應用程序。
球衣:
Jersey 是用於構建 RESTful Web 服務的開源、生產質量、JAX-RS (JSR 311) 參考實現。 但是,它也不僅僅是參考實現。 Jersey 提供了一個 API,以便開發人員可以擴展 Jersey 以滿足他們的需求。
讓我們通過以下步驟開始構建簡單的RESTful API
:
第1步
在 Eclipse => 文件 => 新建 => 動態 Web 項目中。 將其命名為“ CrunchifyRESTJerseyExample
”。

確保您設置:
- 目標運行時:Apache Tomcat v9.0
- 動態網頁模塊版本:4.0
第2步
如果您沒有看到web.xml
(部署描述符),請按照以下步驟操作。 要么
- 右鍵單擊項目
- 選擇
Java EE Tools
- 單擊
Generate Deployment Descriptor Stub
這將在/WebContent/WEB-INF/
文件夾下創建web.xml
文件。
第三步
現在將 Project 轉換為Maven Project
,以便我們可以添加所需的 .jar 文件作為依賴項。
腳步:
- 右鍵單擊項目
- 點擊
Configure
- 選擇選項
Convert to Maven Project
。


只需單擊Finish button
而不進行任何更改。

第四步
打開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
- 點擊源
- 右鍵->新建->類
- 包: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 步
在 Tomcat 上部署項目CrunchifyRESTJerseyExample
。 如果您還沒有這樣做,這裡是有關如何在 Eclipse 上設置 Tomcat 的詳細步驟。
- 轉到服務器選項卡
- 右鍵單擊服務器
- 單擊
Add and Remove Projects
- 從左側選擇項目,然後單擊
Add
- 點擊完成

第十步
- 啟動 Tomcat 服務器 9.0

完整的項目結構:

以下是 Java 構建路徑依賴項:

確保您為此項目使用 JDK 1.8。 啟動 Java 9 – JAXB、JAX-WS、JAF、JTA、CORBA 模塊被刪除,您需要手動將這些模塊添加到您的 Maven pom.xml 文件中。
搞定。
現在讓我們測試一下 RESTful Web 服務。
測試 1: without
參數的攝氏到華氏 Web 服務
鏈接: http://localhost:8080/CrunchifyRESTJerseyExample/crunchify/ctofservice/

測試 2: with
參數的攝氏到華氏 Web 服務

測試 3: without
參數的華氏到攝氏 Web 服務

測試 4: with
參數的華氏到攝氏 Web 服務

RESTFul 客戶端示例:
- 如何使用 Apache HttpClient 創建 RESTful Java 客戶端 - 示例
- 如何使用 Java.Net.URL 創建 RESTful Java 客戶端 - 示例
- 如何使用 Jersey 客戶端創建 RESTful Java 客戶端 - 示例
另一個必須閱讀:
- CrunchifyJSONtoHTML.js – JSON 到 HTML 表格轉換器腳本
- 如何以編程方式在 Java 中生成內存不足 (OOM)
- 如何在一台服務器上運行多個 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 ) |
如果您遇到上述錯誤,請嘗試將以下 maven 依賴項添加到您的 pom.xml 文件中
1 2 3 4 5 |
< dependency > < groupId > org . glassfish . jersey . core < / groupId > < artifactId > jersey - server < / artifactId > < version > 2.27 < / version > < / dependency > |