Crea un servizio RESTful in Java utilizzando JAX-RS e Jersey (da Celsius a Fahrenheit e Fahrenheit a Celsius)
Pubblicato: 2020-03-25
Hai una delle seguenti domande/domande?
- Scrivi un servizio REST Java per convertire Fahrenheit in Celsius e Celcius in Fahrenheit
- REST con Java (JAX-RS) utilizzando Jersey
- Conversione dal metodo Fahrenheit a Celsius in Java
- Aiuto compiti con conversione di gradi (CtoF, FtoC)
- API Java per servizi Web RESTful
- servizi web – Qual è la migliore API REST Java?
- API REST per Java?
- tutorial ctof e ftoc. ctof e ftoc Java Tutorial
- Crea servizi Web RESTful con tecnologia Java
- Framework API Web RESTful per Java
RESTful Service
: Representational State Transfer (REST) ha ottenuto un'ampia accettazione in tutto il Web come alternativa più semplice ai servizi Web basati su SOAP e Web Services Description Language (WSDL).
REST definisce un insieme di principi architetturali in base ai quali è possibile progettare servizi Web incentrati sulle risorse di un sistema, incluso il modo in cui gli stati delle risorse vengono indirizzati e trasferiti su HTTP da un'ampia gamma di client scritti in linguaggi diversi. Se misurato dal numero di servizi Web che lo utilizzano, REST è emerso solo negli ultimi anni come un modello di progettazione di servizi Web predominante. In effetti, REST ha avuto un impatto così grande sul Web che ha per lo più sostituito il design dell'interfaccia basata su SOAP e WSDL perché è uno stile notevolmente più semplice da usare.
RESTful vs. Tutorial SAPONE.

JAX-RS:
L'API Java per i servizi Web RESTful (JAX-RS) è un set di API per il servizio REST dello sviluppatore. JAX-RS fa parte di Java EE6 e consente agli sviluppatori di sviluppare facilmente applicazioni Web REST.
Maglia:
Jersey è l'implementazione di riferimento JAX-RS (JSR 311) open source di qualità per la creazione di servizi Web RESTful. Ma è anche più dell'implementazione di riferimento. Jersey fornisce un'API in modo che gli sviluppatori possano estendere Jersey in base alle loro esigenze.
Iniziamo a creare una semplice RESTful API
con i passaggi seguenti:
Passo 1
In Eclipse => File => Nuovo => Progetto Web dinamico. Chiamalo come " CrunchifyRESTJerseyExample
".

Assicurati di impostare:
- Runtime di destinazione: Apache Tomcat v9.0
- Versione del modulo web dinamico: 4.0
Passo 2
Se non vedi web.xml
(descrittore di distribuzione), segui questi passaggi. O
- Fare clic con il tasto destro del mouse sul progetto
- Seleziona
Java EE Tools
- Fare clic su
Generate Deployment Descriptor Stub
Questo creerà il file web.xml
nella cartella /WebContent/WEB-INF/
.
Passaggio 3
Ora converti Project in Maven Project
in modo da poter aggiungere i file .jar richiesti come dipendenze.
Passi:
- Fare clic con il tasto destro del mouse sul progetto
- Fare clic su
Configure
- Seleziona l'opzione
Convert to Maven Project
.


Basta fare clic sul Finish button
senza apportare modifiche.

Passaggio 4
Apri il file pom.xml
e aggiungi le dipendenze di seguito.
- asm.jar
- jersey-bundle.jar
- json.jar
- jersey-server.jar

Ecco il mio file 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 > |
Passaggio 5
Aggiorna il tuo file web.xml con questo. Ecco la mia copia del file 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 > |
Passaggio 6
- Vai a
Java Resources
- Clicca su src
- Fare clic con il tasto destro -> Nuovo -> Classe
- Pacchetto: com.crunchify.restjersey
- Nome: 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>" ; } } |
Passaggio 7
Allo stesso modo crea 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 ( ) ; } } |
Passaggio 8
Ora puliamo l'area di lavoro di Eclipse e costruiamo il progetto.

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 |
- Per
point 3
sopra, usathese screenshots
: Maven Build, clean install. - Dovresti vedere il messaggio di successo della compilazione.
Passaggio 9
Distribuisci il progetto CrunchifyRESTJerseyExample
su Tomcat. Ecco i passaggi dettagliati su come configurare Tomcat su Eclipse se non l'hai fatto.
- Vai alla scheda Server
- Fare clic con il tasto destro del mouse su Server
- Fare clic su
Add and Remove Projects
- Seleziona il progetto dal lato sinistro e fai clic su
Add
- Fare clic su Fine

Passaggio 10
- Avvia Tomcat Server 9.0

Struttura completa del progetto:

Ecco le dipendenze del percorso di build Java:

Assicurati di utilizzare JDK 1.8 per questo progetto. Avvio di Java 9: i moduli JAXB, JAX-WS, JAF, JTA, CORBA vengono rimossi ed è necessario aggiungerli manualmente al file Maven pom.xml.
Tutto stabilito.
Ora mettiamo alla prova il tuo servizio Web RESTful.
Test 1: servizio web da Celsius a Fahrenheit without
parametri
Collegamento: http://localhost:8080/CrunchifyRESTJerseyExample/crunchify/ctofservice/

Test 2: servizio web da Celsius a Fahrenheit with
parametro

Test 3: servizio web da Fahrenheit a Celsius without
parametri

Test 4: servizio web da Fahrenheit a Celsius with
parametro

Esempi di clienti RESTFull:
- Come creare client Java RESTful utilizzando Apache HttpClient – Esempio
- Come creare client Java RESTful con Java.Net.URL – Esempio
- Come creare un client Java RESTful con il client Jersey - Esempio
Un altro deve leggere:
- CrunchifyJSONtoHTML.js – Script di conversione da JSON a tabella HTML
- Come generare out Of Memory (OOM) in Java in modo programmatico
- Come eseguire più istanze Tomcat su un server?
- Come leggere l'oggetto JSON da un file in Java - Crunchify Tutorial
Hai problemi con l'esecuzione del codice?
Alcuni passaggi di triage:
Inizialmente ho usato la dipendenza jersey-core
. Ma aggiunta anche la dipendenza jersey-server
per evitare problemi di seguito.
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 ) |
Se stai ricevendo un errore superiore, prova ad aggiungere sotto la dipendenza Maven nel tuo file pom.xml
1 2 3 4 5 |
< dependency > < groupId > org . glassfish . jersey . core < / groupId > < artifactId > jersey - server < / artifactId > < version > 2.27 < / version > < / dependency > |