Cree un servicio RESTful en Java usando JAX-RS y Jersey (Celsius a Fahrenheit y Fahrenheit a Celsius)
Publicado: 2020-03-25
¿Tiene alguna de las siguientes consultas/preguntas?
- Escriba un servicio REST de Java para convertir Fahrenheit a Celsius y Celsius a Fahrenheit
- REST con Java (JAX-RS) usando Jersey
- Conversión del método Fahrenheit a Celsius en Java
- Ayuda con la tarea con conversión de grados (CtoF, FtoC)
- API de Java para servicios web RESTful
- servicios web – ¿Cuál es la mejor API REST de Java?
- ¿API REST para Java?
- Tutorial de ctof y ftoc. Ctof y ftoc Tutorial de Java
- Cree servicios web RESTful con tecnología Java
- Marco de API web RESTful para Java
RESTful Service
: la transferencia de estado representacional (REST) ha ganado una amplia aceptación en la web como una alternativa más simple a los servicios web basados en SOAP y el lenguaje de descripción de servicios web (WSDL).
REST define un conjunto de principios arquitectónicos mediante los cuales puede diseñar servicios web que se centren en los recursos de un sistema, incluida la forma en que los estados de los recursos se abordan y transfieren a través de HTTP por una amplia gama de clientes escritos en diferentes idiomas. Si se mide por el número de servicios web que lo utilizan, REST ha emergido en los últimos años como un modelo predominante de diseño de servicios web. De hecho, REST ha tenido un impacto tan grande en la Web que en su mayoría ha desplazado el diseño de interfaz basado en SOAP y WSDL porque es un estilo considerablemente más simple de usar.
REPOSO vs. Tutorial SOAP.

JAX-RS:
La API de Java para servicios web RESTful (JAX-RS) es un conjunto de API para el servicio REST del desarrollador. JAX-RS es parte de Java EE6 y hace que los desarrolladores desarrollen aplicaciones web REST fácilmente.
Jersey:
Jersey es la implementación de referencia JAX-RS (JSR 311) de código abierto y calidad de producción para crear servicios web RESTful. Pero también es más que la implementación de referencia. Jersey proporciona una API para que los desarrolladores puedan ampliar Jersey para satisfacer sus necesidades.
Comencemos a construir una RESTful API
simple con los siguientes pasos:
Paso 1
En Eclipse => Archivo => Nuevo => Proyecto web dinámico. Nómbrelo como " CrunchifyRESTJerseyExample
".

Asegúrate de configurar:
- Tiempo de ejecución de destino: Apache Tomcat v9.0
- Versión del módulo web dinámico: 4.0
Paso 2
Si no ve web.xml
(descriptor de implementación), siga estos pasos. O
- Haga clic derecho en el proyecto
- Seleccionar
Java EE Tools
- Haga clic en
Generate Deployment Descriptor Stub
Esto creará un archivo web.xml
en la carpeta /WebContent/WEB-INF/
.
Paso 3
Ahora convierta Project a Maven Project
para que podamos agregar los archivos .jar necesarios como dependencias.
Pasos:
- Haga clic derecho en el proyecto
- Haga clic en
Configure
- Seleccione la opción
Convert to Maven Project
.


Simplemente haga clic en el Finish button
sin realizar ningún cambio.

Etapa 4
Abra el archivo pom.xml
y agregue las dependencias a continuación.
- asm.jar
- jersey-bundle.jar
- json.jar
- servidor-jersey.jar

Aquí está mi archivo 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 > |
Paso-5
Actualice su archivo web.xml con este. Aquí está mi copia del archivo 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 > |
Paso-6
- Ir a
Java Resources
- Haga clic en origen
- Clic derecho -> Nuevo -> Clase
- Paquete: com.crunchify.restjersey
- Nombre: 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>" ; } } |
Paso-7
De la misma manera 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 ( ) ; } } |
Paso-8
Ahora vamos a limpiar el espacio de trabajo de Eclipse y construir el proyecto.

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 |
- Para
point 3
anterior, usethese screenshots
de pantalla: Maven Build, instalación limpia. - Debería ver el mensaje de compilación exitosa.
Paso-9
Implemente el proyecto CrunchifyRESTJerseyExample
en Tomcat. Aquí hay pasos detallados sobre cómo configurar Tomcat en Eclipse si aún no lo ha hecho.
- Ir a la pestaña Servidor
- Haga clic derecho en Servidor
- Haga clic en
Add and Remove Projects
- Seleccione el proyecto del lado izquierdo y haga clic en
Add
- Haga clic en finalizar

Paso-10
- Inicie el servidor Tomcat 9.0

Estructura completa del proyecto:

Aquí están las dependencias de la ruta de compilación de Java:

Asegúrese de utilizar JDK 1.8 para este proyecto. Inicio de Java 9: los módulos JAXB, JAX-WS, JAF, JTA, CORBA se eliminan y debe agregar esos módulos manualmente a su archivo Maven pom.xml.
Todo listo.
Ahora probemos su servicio web RESTful.
Prueba 1: servicio web Celsius a Fahrenheit without
parámetro
Enlace: http://localhost:8080/CrunchifyRESTJerseyExample/crunchify/ctofservice/

Prueba 2: servicio web de Celsius a Fahrenheit with
parámetro

Prueba 3: servicio web Fahrenheit a Celsius without
parámetro

Prueba 4: servicio web Fahrenheit a Celsius with
parámetro

Ejemplos de clientes RESTFul:
- Cómo crear un cliente Java RESTful usando Apache HttpClient – Ejemplo
- Cómo crear un cliente Java RESTful con Java.Net.URL – Ejemplo
- Cómo crear un cliente Java RESTful con el cliente Jersey: ejemplo
Otro debe leer:
- CrunchifyJSONtoHTML.js – Script convertidor de tabla JSON a HTML
- Cómo generar sin memoria (OOM) en Java programáticamente
- ¿Cómo ejecutar varias instancias de Tomcat en un servidor?
- Cómo leer un objeto JSON desde un archivo en Java – Tutorial de Crunchify
¿Tiene problemas para ejecutar el código?
Algunos pasos de triaje:
Inicialmente usé la dependencia jersey-core
. Pero también se agregó la dependencia jersey-server
para evitar el siguiente problema.
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 obtiene el error anterior, intente agregar la dependencia maven a continuación en su archivo pom.xml
1 2 3 4 5 |
< dependency > < groupId > org . glassfish . jersey . core < / groupId > < artifactId > jersey - server < / artifactId > < version > 2.27 < / version > < / dependency > |