본문 바로가기
스프링

[Spring] ResponseEntity

by 리포터12 2023. 1. 10.
728x90

ResponseEntity
ResponseEntity는 전체 HTTP response 를 나타낸다. (상태 코드, 헤더, 바디)
그래서 HTTP Response를 완전히 구성(설정)하여 사용할 수 있다.

ResponseEntity를 사용하고 싶다면, 엔드 포인트(작업이 끝나는 지점)에서 ResponseEntity를 반환하면 된다.
그럼 스프링이 나머지는 알아서 해준다.


ResponseEntity 는 Generic 타입이다. ( = 응답 본문으로 어떤 유형이든 사용 가능하다.)

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

그리고, 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는 HeaderBuilder 와 그 하위 인터페이스인 BodyBuilder 라는 두 개의 중첩된 빌더 인터페이스를 제공한다.

즉. ResponseEntity의 정적 메서드를 통해 해당 기능에 엑세스 할 수 있다.

아래 코드가 그 간단한 예시 되겟다.

@GetMapping("/hello")
ResponseEntity<String> hello() {
    return ResponseEntity.ok("Hello World!");
}

가장 많이 사용되는 HTTP 상태 코드의 경우, 정적 메서드를 얻는다.

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

또,

BodyBuilder status(HttpStatus status) 와 

BodyBuilder status(int status) 메서드를 사용해 HTTP 상태를 설정할 수 있다.

 

마지막으로, 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.bodyt() 는 BodyBuilder 대신 ResponseEntity를 반환하므로 마지막에 호출해야 한다.

(ResponseEntity 로 반환 할거니)

 

HeaderBuilder 를 사용하면, 응답 본문의 속성을 설정할 수 없게된다.

 

컨트롤러에서 ResponseEntity<T> 객체를 반환하는 작업 진행 중, 

예외와 에러가 발생할 수 있다.

오류 관련 정보(E)를 유저에게-!

 

spring 3.2 는 ExceptionHandler 과 새로운 @COntrollerAdvice 어노테이션을 지원한다.

자세한 내용은 https://www.baeldung.com/exception-handling-for-rest-with-spring 여길 참고 하자.

 

주의!

ResponseEntity 는 몸시 유용하지만, 남용해선 안 된다.

ResponseEntity 외에 요구 사항을 충족시키는 다양하고 단순명료한 옵션들이 존재한다.

깨긋한 코드를 만들자.

=> ResponseEntity 는 강력한만큼 무겁고, 코드가 더러워질 수 있다. 상황에 맞는 옵션을 구사하자.

 

대안

@ResponseBody

 

@ResponseStatus

엔드포인트가 성공적으로 반환되면 Spring 은 HTTP 200 (OK) 응답을 제공한다.

엔드포인트가 예외를 발생시키면 Spring 은 사용할 HTTP 상태를 알려주는 예외 핸들러를 찾는다.

@ResponseStatus 어노테이션으로 이러한 메서드를 spring 에게 알릴 수 있고, spring이 사용자 지정 HTTP status 를 반환한다.

 

Mainpulitate the Response Directly (응답 직접적으로 조작하기)

@GetMapping("/manual")
void manual(HttpServletResponse response) throws IOException {
    response.setHeader("Custom-Header", "foo");
    response.setStatus(200);
    response.getWriter().println("Hello World!");
}

 

Spring은 

 

javax.servlet.http.HttpServletResponse 객체에 직접 접근할 수 있게 해준다.

메서드 인수로 선언만 하면 된다. ㄴ 저작권 문제로 3.0 버전 이후부터는 javax 가 아닌 jakarta 로 이름이 바뀐 모양이다.

 

번역기 돌린 내용이라 내용이 매끄럽지 않은 부분이 있다.

 

출처 :https://www.baeldung.com/spring-response-entity

 

728x90

'스프링' 카테고리의 다른 글

@Autowired  (0) 2023.03.29
No ParameterResolver registered for parameter  (0) 2023.01.30
[Spring] 검증 - @Valid, @validated 동작 원리  (0) 2022.12.29
@Enumerated (value = EnumType.ORDINAL) 지양하는 이유  (0) 2022.12.28
22.12.26 회고  (0) 2022.12.26

댓글