Spring ResponseEntity

반응형

ResponseEntity

REST 방식으로 호출하는 경우 데이터 자체를 전송하기 때문에 데이터를 요청한 쪽에서는 정상적인 데이터인지 비정상적인 데이터인지 구분할 수 있는 방법이 필요합니다. 이를 위해 RESTful 웹 서비스를 개발할 때 `ResponseEntity`를 사용합니다. `ResponseEntity`는 HTTP 응답의 상태 코드, 본문 데이터, 헤더 등을 명시적으로 설정하여 클라이언트와의 통신을 할 수 있습니다. 

  • 상태 코드 설정: HTTP 응답의 상태 코드를 명시적으로 설정 가능합니다.
  • 응답 본문 설정: HTTP 응답의 본문 데이터를 설정할 수 있습니다. JSON, XML , 문자열 등 다양한 데이터 형식을 지원합니다. 제네릭 타입을 사용하여 데이터 타입을 명시할 수도 있습니다.
  • 응답 헤더 설정: HTTP 응답의 헤더를 설정할 수 있습니다. 응답에 특정 헤더 값을 추가하거나 수정할 수 있고, `HttpHeaders` 객체를 사용하여 헤더 값을 설정할 수 있습니다.

 


ResponseEntity 예제

생성자 이용 방법

@GetMapping("/hello")
public ResponseEntity<String> hello() {
    String response = "Hello World!";
    return new ResponseEntity<>(response, HttpStatus.OK);
}
  • ResponseEntity<>(status)
  • ResponseEntity<>(body, status)
  • ResponseEntity<>(headers, status)
  • ResponseEntity<>(body, headers, status)

 

빌더 패턴 활용 방법

@GetMapping("/hello")
public ResponseEntity<String> hello() {
    String response = "Hello World!";
    return ResponseEntity.status(HttpStatus.OK).body(response);
}

 

상태 코드를 바탕으로 미리 빌더 패턴을 구현해놓았기 때문에 아래 코드와 같이 작성해줘도 됩니다.

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

/* *
 * public static BodyBuilder ok() {
 *    return status(HttpStatus.OK);
 * }
 */

 

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

/* *
 * public static <T> ResponseEntity<T> ok(@Nullable T body) {
 *    return ok().body(body);
 * }
 */

ResponseEntity 상태 코드 정적 메서드

  • ResponseEntity.ok(): 200 OK
  • ResponseEntity.created(): 201 Created
  • ResponseEntity.accepted(): 202 Accepted
  • ResponseEntity.nonAuthoritativeInformation(): 203 Non-Authoritative Information
  • ResponseEntity.noContent(): 204 No Content
  • ResponseEntity.resetContent(): 205 Reset Content
  • ResponseEntity.partialContent(): 206 Partial Content
  • ResponseEntity.multipleChoices(): 300 Multiple Choices
  • ResponseEntity.movedPermanently(): 301 Moved Permanently
  • ResponseEntity.found(): 302 Found
  • ResponseEntity.seeOther(): 303 See Other
  • ResponseEntity.notModified(): 304 Not Modified
  • ResponseEntity.temporaryRedirect(): 307 Temporary Redirect
  • ResponseEntity.badRequest(): 400 Bad Request
  • ResponseEntity.unauthorized(): 401 Unauthorized
  • ResponseEntity.forbidden(): 403 Forbidden
  • ResponseEntity.notFound(): 404 Not Found
  • ResponseEntity.methodNotAllowed(): 405 Method Not Allowed
  • ResponseEntity.conflict(): 409 Conflict
  • ResponseEntity.internalServerError(): 500 Internal Server Error
  • ResponseEntity.notImplemented(): 501 Not Implemented
  • ResponseEntity.badGateway(): 502 Bad Gateway
  • ResponseEntity.serviceUnavailable(): 503 Service Unavailable
  • ResponseEntity.gatewayTimeout(): 504 Gateway Timeout
반응형