[Spring] ResponseEntity를 활용한 HTTP Response 처리

Kim Hyen Su·2024년 6월 7일
1

Spring

목록 보기
5/13
post-thumbnail

Spring


개요

자바 개발자를 위한 온라인 리소스 및 교육 플랫폼 중 "Baeldung" 내에서 제공하는 REST API 관련 Tutorial에 대해 학습해보는 시간을 갖겠습니다.

해당 내용은 전적으로 Baeldung에 기재된 내용을 바탕으로 서술되어 있으며, 관련 내용 중 필자가 부족한 개념은 추가로 포스팅할 예정입니다.

📜 참고글

ResponseEntity

Spring에서는 HTTP Response를 처리하는 다양한 방법을 제공합니다.

이 중 이번 포스팅에서는 ResponseEntity 를 사용하여 HTTP Response Body 및 Header를 설정하는 방법에 대해서 살펴보겠습니다.

ResponseEntity는 상태 코드, 헤더, 본문 등 HTTP Response 전체를 나타냅니다. 즉, 이를 사용하여 완전한 HTTP 응답을 구성할 수 있습니다.

@GetMapping("/hello")
ResponseEntity<String> hello() {
    return new ResponseEntity<>("Hello World!", HttpStatus.OK);
}

여러 상황에 따라서 다양한 상태 코드를 반환할 수 있습니다.

@GetMapping("/age")
ResponseEntity<String> age(
  @RequestParam("yearOfBirth") int yearOfBirth) {
 
    if (isInFuture(yearOfBirth)) {
        return new ResponseEntity<>(
          "Year of birth cannot be in the future", 
          HttpStatus.BAD_REQUEST);
    }

    return new ResponseEntity<>(
      "Your age is " + calculateAge(yearOfBirth), 
      HttpStatus.OK);
}

위의 코드를 확인하면, 생일이 지난 경우에 BAD_REQUEST(400)를 응답하고, 아닌 경우 OK(200)을 응답합니다.

또한, ResponseEntity를 사용하면 HTTP 헤더를 설정할 수 있습니다.

@GetMapping("/customHeader")
ResponseEntity<String> customHeader() {
    HttpHeaders headers = new HttpHeaders();
    headers.add("Custom-Header", "foo");
        
    return new ResponseEntity<>(
      "Custom header set", headers, HttpStatus.OK);
}

ResponseEntity는 HeadersBuilder와 하위 인터페이스인 BodyBuilder라는 두 중첩 빌더 인터페이스를 제공합니다.

BodyBuilder accepted();
BodyBuilder badRequest();
BodyBuilder created(java.net.URI location);
HeadersBuilder<?> noContent();
HeadersBuilder<?> notFound();
BodyBuilder ok();

해당 빌더의 status(HttpStatus status) 메서드를 사용하여 HTTP 상태 설정이 가능합니다.

return ResponseEntity.status(HttpStatus.OK).body("come on!");

마지막으로 ResponseEntity<T> BodyBuilder.body(T body) 를 사용하여 HTTP 응답 바디를 설정할 수 있습니다.

@GetMapping("/age")
ResponseEntity<String> age(@RequestParam("yearOfBirth") int yearOfBirth) {
    if (isInFuture(yearOfBirth)) {
        return ResponseEntity.badRequest()
            .body("Year of birth cannot be in the future");
    }

    return ResponseEntity.status(HttpStatus.OK)
        .body("Your age is " + calculateAge(yearOfBirth));
}

사용자 정의 헤더 설정도 가능합니다.

@GetMapping("/customHeader")
ResponseEntity<String> customHeader() {
    return ResponseEntity.ok()
        .header("Custom-Header", "foo")
        .body("Custom header set");
}

BodyBuilder의 body()는 ResponseEntity를 반환하므로 마지막에 호출되어야 합니다.

대안

@ResponseBody

기본적으로 Spring MVC 애플리케이션에서 Controller는 일반적으로 렌더링된 HTML 페이지를 반환합니다.

하지만, 때때로 AJAX를 사용하는 경우에 데이터만 반환해야 하는 경우가 있습니다. 이러한 경우에 Controller 메서드를 @ResponseBody로 표시해주며, Spring은 메서드의 결과값을 HTTP 응답 본문으로 처리해줍니다.

@ResponseStatus

Controller에서 성공적으로 응답이 반환되면 Spring은 HTTP 200 응답 상태코드를 반환합니다. 예외가 발생한 경우 Spring은 HTTP 상태를 알려줄 예외 핸들러를 찾습니다.

@ResponseStatus를 사용하면 응답 처리를 사용자가 정의한 HTTP 응답 상태코드로 반환할 수 있습니다.

응답을 직접 조작하는 방식

Spring을 통해서 javax.servlet.http.HttpServletResponse 객체에 직접 접근이 가능합니다. 메서드 매개변수로 해당 객체를 선언만하면 조작 가능합니다.

Spring은 기본 구현 위에 추상화와 추가 기능을 제공하기 때문에 응답을 이런 방식으로 조작하는 방식은 지양 바랍니다.

profile
백엔드 서버 엔지니어

0개의 댓글