JAX-RS 및 Jersey를 사용하여 Java에서 RESTful 서비스 구축(섭씨에서 화씨 및 화씨에서 섭씨로)
게시 됨: 2020-03-25
아래 쿼리/질문 중 하나가 있습니까?
- 화씨를 섭씨로, 섭씨를 화씨로 변환하는 자바 REST 서비스 작성
- Jersey를 사용하는 Java(JAX-RS)가 있는 REST
- Java에서 화씨에서 섭씨로 변환 방법
- 도 변환(CtoF, FtoC)이 있는 숙제 도움말
- RESTful 웹 서비스용 자바 API
- 웹 서비스 – 최고의 Java REST API는 무엇입니까?
- 자바용 REST API?
- ctof 및 ftoc 튜토리얼. ctof 및 ftoc 자바 튜토리얼
- Java 기술로 RESTful 웹 서비스 생성
- 자바용 RESTful 웹 API 프레임워크
RESTful Service
: REST(Representational State Transfer)는 SOAP 및 WSDL(Web Services Description Language) 기반 웹 서비스에 대한 보다 간단한 대안으로 웹 전반에 걸쳐 널리 수용되고 있습니다.
REST는 다양한 언어로 작성된 다양한 클라이언트가 HTTP를 통해 리소스 상태를 지정하고 전송하는 방법을 포함하여 시스템 리소스에 중점을 둔 웹 서비스를 설계할 수 있는 일련의 아키텍처 원칙을 정의합니다. 이를 사용하는 웹 서비스의 수로 측정하면 REST는 지난 몇 년 동안만 해도 주요 웹 서비스 디자인 모델로 부상했습니다. 실제로 REST는 웹에 큰 영향을 주어 SOAP 및 WSDL 기반 인터페이스 디자인을 대부분 대체했습니다. 사용하기가 훨씬 더 간단한 스타일이기 때문입니다.
RESTFul 대. SOAP 튜토리얼.

JAX-RS:
JAX-RS(Java API for RESTful Web Services)는 개발자 REST 서비스에 대한 API인 경우 집합입니다. JAX-RS는 Java EE6의 일부이며 개발자가 REST 웹 애플리케이션을 쉽게 개발할 수 있도록 합니다.
저지:
Jersey는 RESTful 웹 서비스 구축을 위한 오픈 소스, 프로덕션 품질, JAX-RS(JSR 311) 참조 구현입니다. 그러나 이것은 또한 참조 구현 그 이상입니다. Jersey는 개발자가 필요에 맞게 Jersey를 확장할 수 있도록 API를 제공합니다.
아래 단계에 따라 간단한 RESTful API
빌드를 시작해 보겠습니다.
1 단계
Eclipse => 파일 => 새로 만들기 => 동적 웹 프로젝트에서. 이름을 " CrunchifyRESTJerseyExample
"로 지정합니다.

다음을 설정했는지 확인하십시오.
- 대상 런타임: Apache Tomcat v9.0
- 동적 웹 모듈 버전: 4.0
2 단계
web.xml
(배포 설명자)이 표시되지 않으면 다음 단계를 따르세요. 또는
- 프로젝트를 마우스 오른쪽 버튼으로 클릭
-
Java EE Tools
선택 -
Generate Deployment Descriptor Stub
을 클릭하십시오.
그러면 /WebContent/WEB-INF/
폴더 아래에 web.xml
파일이 생성됩니다.
3단계
이제 프로젝트를 Maven Project
로 변환하여 필요한 .jar 파일을 종속성으로 추가할 수 있습니다.
단계:
- 프로젝트를 마우스 오른쪽 버튼으로 클릭
-
Configure
을 클릭하십시오 -
Convert to Maven Project
선택합니다.


변경하지 않고 Finish button
을 클릭하기만 하면 됩니다.

4단계
pom.xml
파일을 열고 아래 종속성을 추가하십시오.
- asm.jar
- 저지 번들.jar
- json.jar
- 저지 서버.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 Build, 새로 설치. - 빌드 성공 메시지가 표시되어야 합니다.
9단계
Tomcat에 프로젝트 CrunchifyRESTJerseyExample
을 배포합니다. 다음은 Eclipse에서 Tomcat을 설정하지 않은 경우 설정하는 방법에 대한 자세한 단계입니다.
- 서버 탭으로 이동
- 서버를 마우스 오른쪽 버튼으로 클릭
-
Add and Remove Projects
를 클릭하십시오. - 왼쪽에서 프로젝트를 선택하고
Add
를 클릭합니다. - 완료 클릭

10단계
- 톰캣 서버 9.0 시작

완전한 프로젝트 구조:

다음은 Java 빌드 경로 종속성입니다.

이 프로젝트에 JDK 1.8을 사용하고 있는지 확인하십시오. Java 9 시작 – JAXB, JAX-WS, JAF, JTA, CORBA 모듈이 제거되었으며 해당 모듈을 Maven pom.xml 파일에 수동으로 추가해야 합니다.
모든 설정.
이제 RESTful 웹 서비스를 테스트해 보겠습니다.
테스트 1: 매개변수 without
섭씨에서 화씨로 웹 서비스
링크: http://localhost:8080/CrunchifyRESTJerseyExample/crunchify/ctofservice/

테스트 2: 매개변수를 with
섭씨에서 화씨로 웹 서비스

테스트 3: 매개변수 without
화씨에서 섭씨로 웹 서비스

테스트 4: 매개변수 with
화씨에서 섭씨로 웹 서비스

RESTFul 클라이언트 예:
- Apache HttpClient를 사용하여 RESTful 자바 클라이언트를 만드는 방법 – 예제
- 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 ) |
위의 오류가 발생하면 pom.xml 파일에 아래의 maven 종속성을 추가해 보십시오.
1 2 3 4 5 |
< dependency > < groupId > org . glassfish . jersey . core < / groupId > < artifactId > jersey - server < / artifactId > < version > 2.27 < / version > < / dependency > |