RESTful Web Service

By | 2021년 7월 17일
Table of Contents

RESTful Web Service

목표

아래의 내용과 같은 Json 데이타를 반환하는 RESTful Web Service 프로젝트를 생성합니다.

{"id":1,"content":"Hello, World!"}

프로젝트 생성

Hello, World! 프로젝트 생성하기 를 참조해서 신규 프로젝트를 생성합니다.

클래스 생성

위와 같이 service/web 패키지를 생성 후 각각 Greeting.java/GreetingController.java 를 생성해 줍니다.

Greeting.java

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;
    }
}

GreetingController.java

@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));
    }
}

프로젝트 실행

프로젝트 실행 후 아래의 링크를 열어 결과를 확인합니다.

http://localhost:8080/greeting

브라우저를 새로고침하면 카운터가 증가하는 것을 확인할 수 있습니다.

One thought on “RESTful Web Service

  1. Pingback: Spring Boot 시작하기 – 상구리의 기술 블로그

답글 남기기