SeouliteLab

[Java/자바] Spring @ResponseStatus: HTTP 응답 상태 코드 지정하기 본문

프로그래밍

[Java/자바] Spring @ResponseStatus: HTTP 응답 상태 코드 지정하기

Seoulite Lab 2024. 3. 12. 11:04

Spring 프레임워크에서 @ResponseStatus 어노테이션은 컨트롤러 메서드의 HTTP 응답 상태 코드를 지정할 때 사용됩니다. 이 글에서는 @ResponseStatus 어노테이션의 사용법과 예제 코드를 통해 자세히 알아보겠습니다.

1. 기본적인 @ResponseStatus 사용법

가장 간단한 형태의 @ResponseStatus 어노테이션은 다음과 같이 컨트롤러 메서드에 적용됩니다.

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;

@Controller
public class MyController {

    @GetMapping("/example")
    @ResponseStatus(HttpStatus.CREATED)
    public void handleRequest() {
        // 처리 로직
    }
}

위의 예제에서는 /example 요청에 대한 응답 상태 코드를 201(CREATED)로 지정합니다.

2. 특정 예외에 대한 응답 상태 코드 지정하기

@ResponseStatus 어노테이션은 예외가 발생했을 때도 사용할 수 있습니다.

예제 1: 특정 예외에 대한 응답 상태 코드 지정하기

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpStatus;

@RestController
public class MyController {

    @GetMapping("/example")
    public void handleRequest() throws CustomException {
        throw new CustomException();
    }

    @ExceptionHandler(CustomException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public String handleCustomException(CustomException ex) {
        return "CustomException occurred";
    }
}

위의 예제에서는 CustomException이 발생했을 때 응답 상태 코드를 404(NOT_FOUND)로 지정합니다.

3. 예제 코드

다음은 @ResponseStatus 어노테이션을 사용한 예제 코드입니다.

예제 1: 기본적인 @ResponseStatus 사용법

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;

@Controller
public class MyController {

    @GetMapping("/example")
    @ResponseStatus(HttpStatus.CREATED)
    public void handleRequest() {
        // 처리 로직
    }
}

예제 2: 특정 예외에 대한 응답 상태 코드 지정하기

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpStatus;

@RestController
public class MyController {

    @GetMapping("/example")
    public void handleRequest() throws CustomException {
        throw new CustomException();
    }

    @ExceptionHandler(CustomException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public String handleCustomException(CustomException ex) {
        return "CustomException occurred";
    }
}

4. 결론

이상으로 Spring의 @ResponseStatus 어노테이션에 대한 자세한 설명과 예제 코드를 살펴보았습니다. @ResponseStatus 어노테이션을 사용하여 컨트롤러 메서드 또는 예외 발생 시 HTTP 응답 상태 코드를 지정할 수 있습니다.

해시태그: