반응형
여승철
INTP 개발자
여승철
  • 분류 전체보기 (376)
    • CS (16)
      • 면접 준비 (7)
      • 운영체제 (0)
      • 네트워크 (2)
      • HTTP (6)
      • 스프링(Spring) IoC 컨테이너 (0)
      • 알고리즘 (1)
    • Web (13)
    • AWS (6)
    • Java (43)
    • JSP & Servlet (65)
      • 개념 (42)
      • 실습 (23)
    • Spring Framework (33)
    • Spring Boot (10)
    • Spring Data (22)
      • JPA (14)
      • Query DSL (7)
      • Redis (1)
    • Spring Security (9)
    • Spring Batch (4)
    • MyBatis (10)
    • Front-End (51)
      • JS (27)
      • Vue.js (17)
      • React (5)
      • JQuery (0)
      • d3.js (2)
    • DBMS (24)
      • SQL, RDBMS (16)
      • MongoDB (5)
      • Redis (3)
    • Kafka (3)
    • 리눅스 (Linux) (4)
    • 디자인 패턴 (3)
    • VCS (8)
    • API (0)
    • TOOL (3)
    • Reading Book (28)
      • 이펙티브 자바 (11)
      • Clean Code (10)
      • 1분 설명력 (4)
      • HOW TO 맥킨지 문제해결의 기술 (3)
    • C# (4)
    • NSIS (6)
    • ETC (11)

블로그 메뉴

  • 홈
  • 태그

인기 글

태그

  • jsp
  • querydsl
  • 스트림
  • JSTL
  • 디자인 패턴
  • 맥킨지
  • 회원 관리
  • HTTP
  • controller
  • Spring Batch
  • JDBC
  • 게시판
  • EC2
  • ubuntu
  • mybatis
  • Dao
  • servlet
  • 환경 세팅
  • 로그인
  • 이펙티브 자바

최근 댓글

최근 글

hELLO· Designed By 정상우.
여승철

INTP 개발자

Spring ResponseEntity
Spring Framework

Spring ResponseEntity

2022. 9. 21. 14:13
반응형

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
반응형

'Spring Framework' 카테고리의 다른 글

로그인 처리를 위한 UserDetailsService  (0) 2022.10.14
Spring Thymeleaf 살펴보기  (0) 2022.10.06
Spring Redirect: 다른 URL로 리다이렉트  (0) 2022.09.14
Spring 비동기 처리 @Async, CompletableFuture, TaskDecorator  (0) 2022.09.09
Spring 파일 업로드  (0) 2022.09.07
    여승철
    여승철

    티스토리툴바