[Tutorial][Spring] RESTful Web Service

jijang·2021년 1월 22일
0

SPRING

목록 보기
1/2

RESTful Web Service

개요

이 가이드는 Spring을 사용하여, 'Hello, World' RESTful 웹 서비스를 만드는 과정을 안내 합니다.

목표

  • HTTP GET 'http://localhost:8080/greeting' 요청을 수락하는 서비스를 만들 것 입니다.
    이 서비스는 아래와 같이 인사말의 JSON 응답을 줄 것 입니다.
{"id":1,"content":"Hello, World!"}
  • HTTP GET 쿼리 문자열에서 'name' 매개 변수를 사용하여 응답되는 인사말을 사용자 지정 할 수 있습니다.
    기본 값이던 'World' 값을 'name'이 매개 변수의 값으로 변경되어 응답을 줄 것 입니다.
http://localhost:8080/greeting?name=Jijang
{"id":1,"content":"Hello, Jijang!"}

필요사항

  • 작업 시간 15분
  • 좋아하는 Text Editor 또는 IDE 개발 툴
  • JDK 1.8 또는 이상
  • Gradle 4+ 또는 Maven 3.2+

Spring Initialize 시작

모든 spring 어플리케이션은 Spring Initialize(https://start.spring.io/) 로 시작해야 합니다.
아래와 같이 설정을 진행 합니다.

  • Gradle Project
  • Language : Java 11,
  • Spring Boot : 2.4.2
  • Project Metadata : Default
  • Dependencies : Spring Web

생성된 demo.zip 을 프로젝트 관리 폴더에 해제 후 프로젝트를 Open 합니다.
아래는 Gradle로 선택하였을 때 생성되는 build.gradle 파일의 내용 입니다.

plugins {
	id 'org.springframework.boot' version '2.4.2'
	id 'io.spring.dependency-management' version '1.0.11.RELEASE'
	id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-web'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

test {
	useJUnitPlatform()
}

웹서비스 생성

이제 프로젝트 설정을 완료하였으니 웹 서비스를 만들 수 있습니다.
앞의 목표 항목을 작업을 해보겠습니다.

  • HTTP GET 'http://localhost:8080/greeting' 요청을 수락하는 서비스를 만들 것 입니다.
    이 서비스는 아래와 같이 인사말의 JSON 응답을 줄 것 입니다.
{"id":1,"content":"Hello, World!"}
  • HTTP GET 'http://localhost:8080/greeting?name=Jijang' 쿼리 문자열에서 'name' 매개 변수를 사용하여 응답되는 인사말을 사용자 지정 할 수 있습니다.
    기본 값이던 'World' 값을 'name'이 매개 변수의 값으로 변경되어 응답을 줄 것 입니다.
{"id":1,"content":"Hello, Jijang!"}

위 서비스에 대해서 생각 해봅시다.

  • http Get 요청을 처리 (/greeting)
  • 옵션으로 'name'이라는 query String 입력 (/greeting?name=Jijang)
  • 응답 값의 id 값은 인사말의 고유 식별자
  • 응답 값의 content 는 인사말의 텍스트

하여 인사말(greeting)을 모델링한 클래스를 생성해보겠습니다.

모델 생성

src/main/java/com/example/demo/Greeing.java

package com.example.demo;

public class Greeting {

    private final long id;
    private final String content;

    public Greeting(long id, String content) {
        this.id = id;
        this.content = content;
    }

    public long getId() {
        return id;
    }

    public String getContent() {
        return content;
    }
}

컨트롤러 생성

RESTful 웹서비스 HTTP 요청은 컨트롤러에 의해 처리됩니다.
@RestController 어노테이션을 통하여 컨트롤러가 구성되며, /greeting 요청에 대하여 Greeting 인스턴스를 반환합니다.

src/main/java/com/example/demo/GeetingController.java

package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.atomic.AtomicLong;

@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @GetMapping("/greeting")
    public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
        return new Greeting(counter.incrementAndGet(), String.format(template, name));
    }
}

0개의 댓글