Créez un service RESTful en Java en utilisant JAX-RS et Jersey (Celsius en Fahrenheit et Fahrenheit en Celsius)
Publié: 2020-03-25
Avez-vous l'une des requêtes/questions ci-dessous ?
- Écrire un service Java REST pour convertir Fahrenheit en Celsius et Celcius en Fahrenheit
- REST avec Java (JAX-RS) en utilisant Jersey
- Conversion de la méthode Fahrenheit à la méthode Celsius en Java
- Aide aux devoirs avec conversion de diplômes (CtoF, FtoC)
- API Java pour les services Web RESTful
- services web – Quelle est la meilleure API Java REST ?
- API REST pour Java ?
- tutoriel ctof et ftoc. Tutoriel Java ctof et ftoc
- Créez des services Web RESTful avec la technologie Java
- Cadre d'API Web RESTful pour Java
RESTful Service
: le transfert d'état représentatif (REST) a été largement accepté sur le Web en tant qu'alternative plus simple aux services Web basés sur SOAP et le langage de description de services Web (WSDL).
REST définit un ensemble de principes architecturaux par lesquels vous pouvez concevoir des services Web qui se concentrent sur les ressources d'un système, y compris la manière dont les états des ressources sont adressés et transférés via HTTP par un large éventail de clients écrits dans différents langages. Si mesuré par le nombre de services Web qui l'utilisent, REST est apparu ces dernières années seulement comme un modèle prédominant de conception de services Web. En fait, REST a eu un tel impact sur le Web qu'il a largement remplacé la conception d'interface basée sur SOAP et WSDL, car il s'agit d'un style considérablement plus simple à utiliser.
REPOSANT Vs. Tutoriel SOAP.

JAX-RS :
L'API Java pour les services Web RESTful (JAX-RS) est un ensemble d'API pour le service REST du développeur. JAX-RS fait partie de Java EE6 et permet aux développeurs de développer facilement des applications Web REST.
Jersey:
Jersey est l'implémentation de référence open source JAX-RS (JSR 311) de qualité de production pour la création de services Web RESTful. Mais c'est aussi plus que l'implémentation de référence. Jersey fournit une API afin que les développeurs puissent étendre Jersey en fonction de leurs besoins.
Commençons à créer une RESTful API
simple avec les étapes ci-dessous :
Étape 1
Dans Eclipse => Fichier => Nouveau => Projet Web Dynamique. Nommez-le « CrunchifyRESTJerseyExample
».

Assurez-vous de définir :
- Exécution cible : Apache Tomcat v9.0
- Version du module Web dynamique : 4.0
Étape 2
Si vous ne voyez pas web.xml
(descripteur de déploiement), suivez ces étapes. OU
- Clic droit sur le projet
- Sélectionnez
Java EE Tools
- Cliquez sur
Generate Deployment Descriptor Stub
Cela créera un fichier web.xml
sous le dossier /WebContent/WEB-INF/
.
Étape 3
Maintenant, convertissez Project en Maven Project
afin que nous puissions ajouter les fichiers .jar requis en tant que dépendances.
Pas:
- Clic droit sur le projet
- Cliquez sur
Configure
- Sélectionnez l'option
Convert to Maven Project
.


Cliquez simplement sur le Finish button
sans apporter de modifications.

Étape 4
Ouvrez le fichier pom.xml
et ajoutez les dépendances ci-dessous.
- asm.jar
- maillot-bundle.jar
- json.jar
- jersey-server.jar

Voici mon fichier 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 > |
Étape-5
Mettez à jour votre fichier web.xml avec celui-ci. Voici ma copie de fichier 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 > |
Étape-6
- Aller aux
Java Resources
- Cliquez sur src
- Clic droit -> Nouveau -> Classe
- Paquet : com.crunchify.restjersey
- Nom : 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>" ; } } |
Étape-7
De la même manière, créez 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 ( ) ; } } |
Étape-8
Maintenant, nettoyons l'espace de travail eclipse et construisons le projet.

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 |
- Pour
point 3
ci-dessus, utilisezthese screenshots
d'écran : Maven Build, installation propre. - Vous devriez voir le message de réussite de la construction.
Étape-9
Déployez le projet CrunchifyRESTJerseyExample
sur Tomcat. Voici les étapes détaillées sur la façon de configurer Tomcat sur Eclipse si vous ne l'avez pas encore fait.
- Allez dans l'onglet Serveur
- Clic droit sur Serveur
- Cliquez sur
Add and Remove Projects
- Projet de sélection du côté gauche et cliquez sur
Add
- Cliquez sur terminer

Étape-10
- Démarrer le serveur Tomcat 9.0

Structure complète du projet :

Voici les dépendances du chemin de compilation Java :

Assurez-vous d'utiliser JDK 1.8 pour ce projet. À partir de Java 9 - Les modules JAXB, JAX-WS, JAF, JTA, CORBA sont supprimés et vous devez ajouter ces modules manuellement à votre fichier Maven pom.xml.
Tout est prêt.
Testons maintenant votre service Web RESTful.
Test 1 : Service Web Celsius vers Fahrenheit without
paramètre
Lien : http://localhost:8080/CrunchifyRESTJerseyExample/crunchify/ctofservice/

Test 2 : Service Web Celsius à Fahrenheit with
paramètre

Test 3 : Webservice Fahrenheit vers Celsius without
paramètre

Test 4 : Service Web Fahrenheit vers Celsius with
paramètre

Exemples de clients RESTFul :
- Comment créer un client Java RESTful à l'aide d'Apache HttpClient - Exemple
- Comment créer un client Java RESTful avec Java.Net.URL - Exemple
- Comment créer un client Java RESTful avec le client Jersey - Exemple
Un autre doit lire:
- CrunchifyJSONtoHTML.js - Script de conversion de table JSON en HTML
- Comment générer une mémoire insuffisante (OOM) en Java par programmation
- Comment exécuter plusieurs instances de Tomcat sur un seul serveur ?
- Comment lire un objet JSON à partir d'un fichier en Java - Tutoriel Crunchify
Vous rencontrez des difficultés pour exécuter du code ?
Quelques étapes de tri :
Au départ, j'ai utilisé la dépendance jersey-core
. Mais ajout de la dépendance jersey-server
pour éviter le problème ci-dessous.
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 ) |
Si vous obtenez l'erreur ci-dessus, essayez d'ajouter la dépendance maven ci-dessous dans votre fichier pom.xml
1 2 3 4 5 |
< dependency > < groupId > org . glassfish . jersey . core < / groupId > < artifactId > jersey - server < / artifactId > < version > 2.27 < / version > < / dependency > |