소개 :이 기사는 Spring Boot를 사용하여 간단한 휴식 서비스를 만드는 데 도움이됩니다.
당신은 배울 것입니다
이 튜토리얼에 사용 된 나머지 서비스
이 자습서에서는 적절한 URI 및 HTTP 방법을 사용하여 세 가지 서비스를 작성합니다.
@getMapping ( "/whitsing/{wiching}/courses") : 특정 학생이 요청 메소드를 사용하여 등록한 과정 및 샘플 URI/whitues/whenudent1/코스를 쿼리 할 수 있습니다.
@getMapping ( "/whitsing/{wiching/{studentId}/courses/{courseID}") : 요청 방법을 사용하여 URI/whenings/student1/Course/Course1을 사용하여 특정 학생에 대한 특정 코스를 얻을 수 있습니다.
@postmapping ( "/whitsing/{windentid}/courses") : Uuri/Student/Student1/Courses에 게시물 요청을 보내서 학생들을위한 코스를 등록 할 수 있습니다.
필요한 도구
완전한 Spring Boot Rest Maven 프로젝트 코드 예제
GitHub 저장소에는 모든 코드 예제 -https://github.com/in28minutes/in28minutes.github.io/tree/master/code-zip-files가 포함되어 있습니다
단위 및 통합 테스트를 통한 휴식 서비스
웹 사이트-스프링 부트 레스트 서비스 -simplerestserviceswithUnitAndEgrationTests.zip
휴식은 무엇입니까?
REST는 표현 상태 전이를 나타냅니다. REST는 일련의 아키텍처 제약을 지정합니다. 이러한 조건을 충족하는 모든 서비스를 편안한 서비스라고합니다.
편안한 웹 서비스를위한 5 가지 중요한 조건 :
Richardson 성숙 모델
Richardson 성숙도 모델은 RESTful 웹 서비스의 성숙도를 식별하는 데 사용됩니다. 다음은 다양한 수준과 특성입니다.
레벨 0 : REST 스타일로 비누 웹 서비스를 노출시킵니다. 노출 된 작업은 REST 서비스 (http : // server/getposts, http : // server/deleteposts, http : // server/dothis, http : // server/dothat 등)를 사용합니다.
레벨 1 : 올바른 URI (명사 사용)를 사용하여 리소스를 노출시킵니다. 예를 들면 다음과 같습니다. http : // server/convers, http : // server/accounts/10. 그러나 HTTP 방법은 사용되지 않습니다.
레벨 2 : 리소스는 올바른 URI + HTTP 방법을 사용합니다. 예를 들어 계정을 업데이트하려면 풋을 수행해야합니다. 계정을 만들고 게시물을 수행합니다. URI는 게시물/1/댓글/5, 계정/1/friends/1처럼 보입니다.
레벨 3 : 증오. 요청 된 정보뿐만 아니라 서비스 소비자가 취할 수있는 다음 가능한 조치를 이해할 수 있습니다. Facebook 사용자에 대한 정보를 요청할 때 REST 서비스는 최근 게시물을 얻는 방법, 최근 의견을 얻는 방법 및 친구 목록을 검색하는 방법에 대한 사용자 세부 정보 및 정보를 반환 할 수 있습니다.
적절한 요청 방법을 사용하십시오
항상 HTTP 방법을 사용하십시오. 각 HTTP 방법의 모범 사례는 다음과 같습니다.
GET : 아무것도 업데이트해서는 안됩니다. Idempotent (동일한 결과를 여러 번이라고 함). 가능한 반환 코드 200 (OK) + 404 (찾을 수 없음) + 400 (불량 요청)
게시물 : 새로운 리소스를 만들어야합니다. 이상적으로는 JSON을 반환하고 새로 생성 된 리소스에 링크하십시오. 가능할 때마다 동일한 반환 코드를 사용하십시오. 또한 : 리턴 코드 201 (생성)가 가능합니다.
PIT : 알려진 리소스를 업데이트하십시오. 예 : 고객 세부 정보를 업데이트합니다. 가능한 반환 코드 : 200 (OK)
삭제 : 리소스를 삭제하는 데 사용됩니다.
프로젝트 구조
다음 스크린 샷은 우리가 생성 할 프로젝트의 구조를 보여줍니다.
몇 가지 세부 사항 :
Spring Initializr Boot를 사용하여 REST 서비스를 만듭니다
Spring Initializr로 휴식 서비스를 만드는 것은 매우 쉬운 케이크입니다. 우리는 Spring Web MVC를 웹 계층 프레임 워크로 사용합니다.
Spring initializr http://start.spring.io/는 Spring Boot 프로젝트를 작성하는 훌륭한 도구입니다.
위 그림과 같이 다음 단계를 수행해야합니다.
Spring Initializr을 시작하고 다음을 선택하십시오
com.in28minutes.springboot를 그룹으로 선택하십시오
학생 서비스를 유물로 선택하십시오
다음 종속성을 선택하십시오
프로젝트를 생성하려면 클릭하십시오.
프로젝트를 일식으로 가져옵니다. 파일 -> 가져 오기 -> 기존 Maven 프로젝트.
이 프로젝트의 모든 파일을 알고 싶다면 계속 읽을 수 있습니다.
응용 프로그램 비즈니스 계층 구현
모든 응용 프로그램에는 데이터가 필요합니다. 실제 데이터베이스와 상호 작용하는 대신 메모리 내 데이터 저장소 인 ArrayList를 사용합니다.
학생은 여러 과정을 수강 할 수 있습니다. 과정에는 ID, 이름, 설명 및 과정을 완료하는 단계 목록이 있습니다. 학생에게는 신분증, 이름, 설명 및 현재 등록하고있는 과정 목록이 있습니다. StudentService는 다음과 같은 공개 방법을 제공합니다.
공개 목록 RetrieveAllStudents () - 모든 학생의 세부 정보를 검색합니다
공개 학생 회고 (String StudentId) - 특정 학생 세부 정보를 검색합니다
공개 목록 검색자 (String StudentID) - 모든 과정 검색 학생 등록
공개 코스 검색 (String StudentId, String CourseID) - 학생이 등록한 특정 코스의 세부 정보 검색
공개 코스 AddCourse (String Studentid, Course Course) - 기존 학생들에게 코스 추가
서비스 클래스 StudentService와 모델 클래스 코스 및 학생을 구현하려면 다음 파일을 참조하십시오.
몇 가지 Get Rest Services를 추가하십시오
REST 서비스 StudentController는 여러 GET 서비스를 노출시킵니다.
package com.in28minutes.springboot.controller; import java.util.list; import org.springframework.bean.beans.annotation.autowired; import org.sprameframework.bind.bind.annotation.getmapping; import org.spramework.web.bind.bind.antation org.springframework.web.bind.annotation.restcontroller; import com.in28minutes.springboot.model.course; import com.in28minutes.springboot.service.studentservice; @RestControllerPublic Class StudentController {@autowiredprivice windentErvice; @GetMapping ( "/whitdent/{windentId}/courses") public list <course> retrievecoursesforstudent (@pathvariable stinding studentId) {return wintentervice.retrieveCours (windentId);}@getMapping ( "/whitding/{widentId}/courseid}")) StudentId,@pathVariable String CourseID) {return wintentervice.retrievecourse (StudentId, CourseId);}}}우체부를 사용하여 GET 서비스를 수행하십시오
우리는 서비스를 테스트하기 위해 http : // localhost : 8080/student/student1/courses/course1에 대한 요청을 시작합니다. 응답은 다음과 같습니다.
{ "ID": "Course1", "Name": "Spring", "Description": "10 Steps", "Steps": [ "Maven 학습", "가져 오기 프로젝트", "첫 번째 예", "두 번째 예"]}아래 그림은 Postman의 Get Service를 실행하는 방법을 보여줍니다.
포스트 휴식 서비스를 추가하십시오
자원 생성이 성공하면 우편 서비스는 생성 된 상태를 반환해야합니다 (201).
@postmapping ( "/whitsing/{windentId}/courses") 공개 응답 <void> regis servleturicomponentsbuilder.fromcurrentRequest (). Path ( "/{id}"). buildandexpand (course.getId ()). touri (); return responsentity.created (location) .build ();}휴식 후 서비스를 실행하십시오
샘플 요청은 다음과 같습니다. 여기에는 과정에 등록한 학생들의 모든 세부 사항이 포함되어 있습니다.
{ "name": "microservices", "description": "10 Steps", "Steps": [ "물건을 끊는 방법을 배우십시오", "모든 것을 자동화하는 방법", "재미"}}다음 이미지는 Postman에서 포스트 서비스를 실행하는 방법을 보여줍니다. 바디 탭으로 이동하여 RAW를 선택하십시오. 드롭 다운 메뉴에서 JSON을 선택하십시오. 위의 요청을 신체에 복사하십시오.
우리가 사용하는 URL은 http : // localhost : 8080/whitsing/student1/courses입니다.
완전한 코드 예제
pom.xml
<? xml version = "1.0"encoding = "utf-8"?> <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</modelversion> groupid>com.in28minutes.springboot</groupid> artifactid > Student-Services </artifactid> <bersion> 0.0.1-snapshot </version> <packaging> jar </packaging> <name> 학생-서비스 </name> <description> 데모 Spring Boot 프로젝트 </descript> <부모> <groupid> org.springframework.boot </groupId> <artifactid> Spring-Boot-Starter-Parent </artifactid> <4.4. Release </version> <!-리포지토리에서 부모 -> </parent> <properties> <project.build.sourceencoding> utf-8 </project.build.sourceencoding> <project.reporting.outputencoding> utf-8 </project.reporting.outputencoding> <java.version> 1.8 </java.version> </properties> </properties> < 종속성> <groupid> org.springframework.boot </groupid> <artifactid> 스프링-부트-스타터-승인기 </artifactid> </dependency> <groupide> <groupid> org.springframework.boot </groupid> <artifactid> spring-boot-starter-web </arepifactid> 종속성> <pectionency> <groupId> org.springframework.boot </groupid> <artifactid> spring-boot-devtools </artifactid> <scope> 런타임 </scope> </spectency> <groupid> org.spramework.boot </group-hopt> spring-hoot- Starter-Test </artifactid> <scope> 테스트 </scope> </fectionement> </fectionements> <fuglin> <plugin> <plugin> <groupid> org.springframework.boot </groupid> <artifactid> spring-boot-maven-plugin </artifactid> </plugins> </project> </project>
SRC/MAIN/JAVA/COM/IN28MINUTES/SPRINGBOOT/CONTROLER/StudentController.java
import java.net.uri; import java.util.list; import org.springframework.beans.beans.annotation.autowired; import org.springframework.http.responesentity; import org.sprameframework.wb.band.annotation.getmapping; import org.springframework.web.bind.annotation.pathvariable; import org.springframework.web.bind.annotation.postmapping; import org.springframework.web.bind.annotation.requestbody; import org.springframework.web.bind.annotation.restcontroller; org.springframework.web.servlet.support.servleturicomponentsbuilder; import com.in28minutes.springboot.model.course; import com.in28minutes.springboot.service.studentservice; @restcontrollerpublic classe stutentcontroller windentErvice; @GetMapping ( "/whitdent/{windentId}/courses") 공개 목록 <course> 검색어 스터드 (@pathvariable String) {return wintentervice.retrieveCourses (windentId);}@getMapping ( "/whitding/{StudentId}/coursid}")) StudentId,@PathVariable String CourseId) {return wintentervice.retrievecourse (studentId, courseId);}@postMapping ( "/whitder/{studentId}/courses") probliceNtity <void> RegisterStudentForcourse (@PathVariable String, @RequestBody Course NewCcourse) {windentID. windervices. null) return responsentity.nocontent (). build (); uri location = servleturicomponentsBuilder.fromCurrentRequest (). Path ( "/{id}"). buildAndexPand (course.getId ()). touri (); 반환 응답.src/main/java/com/in28minutes/springboot/model/course.java
import java.util.list; public class course {private string id; private string id; private String name; private String description; private string <string> 단계; // com.fasterxml.jackson.databind.jsonMappingException : // com.in28minutes.springboot.model.course의 인스턴스를 구성 할 수 없습니다. 기본 생성자 또는 제작자 또는 // 유형 정보를 추가/활성화해야 할 필요가 있습니까?) 공개 코스 () {} 공개 코스 (문자열 ID, 문자열 이름, 문자열 설명, 목록 <string> 단계) {super (); this.id = id; this.name = name; this.description; this.steps = 단계;} public string getid (return id; id;} public string getDescription () {return description;} public String getName () {return name;} public list <string> getSteps () {return steps;}@retudPublic String toString () {return string.format ( "id =%s, name =%s, description =%s, stept =%s], id, desction, desction, steps, id) hashcode () {final int prime = 31; int result = 1; result = prime * result + ((id == null)? 0 : id.hashcode ()); return result;}@retainpublic boolean equals (object obj) {if (this == obj) return true; (코스) obj; if (id == null) false를 반환한다.SRC/MAIN/JAVA/COM/IN28MINUTES/SPRINGBOOT/MODEL/Student.java
package com.in28minutes.springboot.model; import java.util.list; public class student {private String id; 개인 문자열 이름; 개인 문자열 설명; 개인 목록 <course> 코스; 공개 학생 (문자열 ID, 문자열 이름, 문자열 설명, 목록 <course> 코스) {super (this.id = id; this.name = this. this. String getId () {return id;} public void setId (string id) {this.id = id;} public String getName () {return name;} public void setName (String name) {this.name = name;} public string getDescription (} public void setdescription (threat) {theverction (description);} {return courses;} public void setcourses (list <course> 코스) {this.courses = courses;}@attradePublic String toString () {return string.format ( "학생 [id =%s, name = s, description =%s, cours =%s]", ID, 이름, 코스);SRC/MAIN/JAVA/COM/IN28MINUTES/SPRINGBOOT/SERVICE/SUSPINSERVICE.java
package com.in28minutes.springboot.service; import java.math.biginteger; import java.security.securerandom; import java.util.arraylist; import java.util.arrays; import java.util.list; import org.spramepramework.component; import; com.in28minutes.springboot.model.course; com.in28minutes.springboot.model.student; @componentpublic class videntervice {private static list <student> 학생 = new arraylist <> (); new 코스 코스 1 = 새로운 코스 ( "코스 1", "10 단계", "10 단계" Maven ","수입 프로젝트 ","첫 번째 예 ","두 번째 예 "); 코스 코스 2 = 새로운 코스 ("Course2 ","Spring MVC ","10 예제 ", Arrays.Aslist ("Learn Maven ","Import Project ","첫 번째 예 ","두 번째 예제 "); 코스 3 = New Course ("Spring 3 ","학습 ","학습 ","학습 " 봄 ","스프링 MVC ","첫 번째 예 ","두 번째 예 ")); 코스 코스 4 = 새로운 코스 ("코스 4 ","Maven ","인터넷에서 가장 인기있는 Maven 코스! ", Arrays.Aslist ("pom.xml ","Build Life Cycle ","Parent Pom ","학생 범위 = New Student = New Student ( ","ranga " Karanam ","등산객, 프로그래머 및 건축가 ", New Arraylist <> (Arrays.Aslist (Course1, Course2, Course3, Course4)); Student Satish = New Student ("Student2 ","Satish T ","Satish T ","Satish T ","Programer and Architect ", New Arraylist (Course.aslist) Course4)))))))); 학생 .add (ranga); student.add (satish);} public list <gully list <guldrieveallstudents () {반품 학생;} 공개 학생 회고 (String StudentId) {for (학생 학생 : 학생) {if (student. {학생 학생 = retrieveStudent (studentId); if (학생 == NULL) {return null;} retud student.getCourses ();} 공개 코스 검색 (String StudentId, String CourseId) {Student Student = retrieveStudent (StudentID); if (Student == null) {return null;} (코스 :). (Course.getId (). Equals (CourseId)) {return course;}} return null;} private securerandom random = new securerandom (); 공개 코스 AddCourse (String StudentId, Course Course) {Student Student = retrieveStudent (StudentID); if (Student == null) {return null;} strand randomId = new biginteger (130, random) .tostring (32); course.setId (randomId); student.getCourses (). Add (코스); 반환 코스;}}src/main/java/com/in28minutes/springboot/wintentervicesapplication.java
패키지 com.in28minutes.springboot; import org.springframework.springApplication; import org.springframework.boot.autoconfigure.springbootApplication; @springbootapplicationPublic ClassePliceSapplication {public static void main (String [] argss). {springApplication.run (winitedervicesApplication.class, args);}}위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.