[Spring Boot] ResponseEntity와 HttpStatus

배규리·2023년 11월 24일

SpringBoot 개발 기록

목록 보기
1/2
post-thumbnail

교보 정보 통신 애플 B2B 코드 분석을 하던 중 아래와 같은 코드를 발견했다.

return new ResponseEntity<>(headers, HttpStatus.FOUND);

해당 메소드의 반환 타입은 ResponseEntity 였다.
기존에 해당 타입으로 반환할 때 난 항상 void가 아닌 Entity나 DTO를 넣어줬어서 그런지 왜 굳이 여기에 반환하지 라는 의문이 들었다!🤔

그래서 검색을 해보니

HttpStatus.FOUND: HTTP 상태코드 중 하나로, 숫자 코드 302에 해당한다. 즉, 리다이렉션을 의미하며, 클라이언트에게 어떤 리다이렉션 위치로 이동할 것인지를 나타내는 헤더와 함께 사용된다.

ResponseEntity<>(headers, HttpStatus.FOUND): 새로운 ResponseEntity객체를 생성하여 해당 헤더와 상태 코드를 포함시키고, 이를 메서드 호출자에게 반환한다. 이는 클라이언트에게 'FOUND' 응답을 전송하고 어딘가로 리다이렉션을 수행하라고 알려준다.

@GetMapping("/api/payment/fail")
@Operation(hidden = true)
public ResponseEntity<Void> failKakaopay(
        @RequestParam("orderId") String orderId,
        @RequestParam("redirect") String redirect) 
{
        
  		orderService.disableOrderWithPaymentState(Long.valueOf(orderId), PaymentState.PAYMENT_FAILED);
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(URI.create(redirect));

        return new ResponseEntity<>(headers, HttpStatus.FOUND);
 }

위의 코드는 kakaopay결제를 실패했을 때 redirect해주는 API를 구현한 Controller의 일부분이다. HttpHeaders 객체를 생성해주고, 인자로 받아온 redirect라는 URI로 리다이렉트한다.

참고 문헌

https://a1010100z.tistory.com/106

profile
백엔드 개발은 취미인 AI 개발자🥹

0개의 댓글