본문 바로가기
개발&프로그래밍

[Spring] 스프링 웹 어노테이션 (Spring Web Annotation)

by 재아군 2022. 3. 15.

Spring에서의 Spring Web 어노테이션을 이용하여 RESTful 웹 서비스를 만들어보자.

 

 

http://localhost:8080/greeting API GET 요청으로 아래의 JSON 응답을 받는 API를 작성해보자.

 

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

 


먼저 greeting 모델 클래스를 만들자.

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

 

스프링에서 Jackson JSON 라이브러리를 이용하여 Greeting 타입의 인스턴스를 자동으로 JSON으로 marshal 해준다.

 

 

Resource Controller 생성하기

package com.example.demo;

import org.springframework.web.bind.annotation.*;

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

 

@RestController 어노테이션

RESTful 웹 서비스를 구축하는 Spring의 접근 방식에서 HTTP 요청은 컨트롤러에 의해 처리됩니다.

@RestController 어노테이션이 붙여진 GreetingController는 Greeting의 새 인스턴스를 반환하여 /greeting에 대한 GET 요청을 처리합니다. @RestController는 @Controller와 @ResponseBody 어노테이션을 포함하고 있습니다.

 

 

@GetMapping 어노테이션 

/greeting에 대한 HTTP GET 요청이 Greeting() 메서드에 매핑되도록 합니다.

 

@RequestParam 어노테이션 

@RequestParam은 쿼리 문자열 파라미터 name의 값을 greeting() 메서드의 name 파라미터에 바인딩합니다.

요청할때 name 파라미터가 없으면 디폴트로 World 값을 초기화해줍니다.

 

 

이제 아래처럼 Spring Boot의 SpringApplication.run() 이 있는 main 메소드를 실행해볼까요?

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class DemoApplication {
	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}
}

 

 

웹브라우저에서 http://localhost:8080/greeting 로 접속해보면, 아래와 같이 응답이 오는걸 확인할 수 있습니다.

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

 

 

http://localhost:8080/greeting?name=Jaea 로 접속해보면, 입력한 name값이 바뀌었는지 확인할 수 있습니다.

{"id":2,"content":"Hello, Jaea!"}

댓글