Spring Boot - ResponseEntity 클래스

2025. 1. 11. 01:16·Spring
반응형

ResponseEntity

Spring Framework에서 HTTP 응답을 제어할 수 있는 클래스이다. 주로 Web Apllication에서 RESTful API를 구현할 때 사용되며, 본문(body), 상태 코드(status code), 헤더(headers) 등을 설정하는데 사용한다.

 

주요 특징

  • Body : 응답의 본문을 설정한다. JSON, 문자열, 객체 등을 반환할 수 있다.
  • Status Code : HTTP 상태 코드를 설정할 수 있다. 200 OK, 404 Not found, 201 Created 등이 있다.
  • Headers : HTTP 응답 헤더를 설정할 수 있다. Content-Type, Authroization 등의 헤더를 추가할 수 있다.

 

기본 사용법

@GetMapping("/message")
public ResponseEntity<String> getMessage() {
    String message = "Hello, world!";
    return new ResponseEntity<>(message, HttpStatus.OK);  // 200 OK 상태 코드와 메시지 반환
}

 

200 OK 코드와 함께 "Hello, world!"라는 메세지를 반환한다.

 

상태 코드 반환하기

@GetMapping("/not-found")
public ResponseEntity<Void> notFound() {
    return ResponseEntity.notFound().build();  // 404 Not Found 상태 코드만 반환
}

 

응답 본문 없이 404 Not Found 상태 코드를 반환한다.

 

파일 다운로드 응답

@GetMapping("/download")
public ResponseEntity<byte[]> downloadFile() {
    byte[] fileData = getFileData();  // 파일 데이터를 가져오는 메서드
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    headers.setContentDisposition(ContentDisposition.attachment().filename("file.txt").build());
    
    return new ResponseEntity<>(fileData, headers, HttpStatus.OK);  // 파일 데이터와 함께 헤더를 설정
}

 

파일을 다운로드하는 응답을 보낼 때 Content-Disposition 헤더를 사용하여 파일 다운로드를 처리한다.

 

쿠키 설정

@GetMapping("/set-cookie")
public ResponseEntity<String> setCookie() {
    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.SET_COOKIE, "username=JohnDoe; Max-Age=3600; HttpOnly");
    return new ResponseEntity<>("Cookie set successfully", headers, HttpStatus.OK);  // 쿠키를 설정하여 반환
}

 

HttpHeaders를 통해 쿠키를 응답 헤더에 추가할 수 있다.

 

 

사용자 정의 응답

@GetMapping("/status")
public ResponseEntity<Map<String, String>> getStatus() {
    Map<String, String> status = new HashMap<>();
    status.put("status", "success");
    status.put("message", "Everything is working!");

    return ResponseEntity
            .status(HttpStatus.OK)  // 상태 코드 설정
            .body(status);  // 응답 본문 설정
}

 

Map을 사용하여 JSON 형태의 응ㄷ바을 반환하며, HTTP 상태 코드를 명시적으로 설정한다.

 

ResponseEntity의 주요 메소드

  • ResponseEntity.ok(): 200 OK 상태 코드와 함께 본문 반환
  • ResponseEntity.created(): 201 Created 상태 코드와 함께 본문 반환
  • ResponseEntity.noContent(): 204 No Content 상태 코드 (본문 없이 응답)
  • ResponseEntity.badRequest(): 400 Bad Request 상태 코드와 함께 본문 반환
  • ResponseEntity.status(): 명시된 상태 코드로 응답 반환

RESTful하게 코드를 작성하려면 주요 메소드에 따라 규칙을 지키는 것이 좋을듯 하다. 

 

 

'Spring' 카테고리의 다른 글

POSTMAN 테스트의 한계, SPRING TEST 도입(단위 테스트)  (1) 2025.02.07
Spring Boot - Querydsl  (0) 2025.01.15
Spring Boot - Lombok  (0) 2024.04.03
Spirng Boot - REST API로 CRUD 만들기  (0) 2024.04.03
Spring Security 살펴보기  (0) 2024.02.22
'Spring' 카테고리의 다른 글
  • POSTMAN 테스트의 한계, SPRING TEST 도입(단위 테스트)
  • Spring Boot - Querydsl
  • Spring Boot - Lombok
  • Spirng Boot - REST API로 CRUD 만들기
CHun2
CHun2
천천히, 하나씩
  • CHun2
    훈이의 개발일기
    CHun2
  • 전체
    오늘
    어제
    • 분류 전체보기 (75)
      • Computer Structure (4)
      • BeakJoon (3)
      • Data Structures & Algorithm.. (12)
      • Database (2)
      • Design pattan (2)
      • Docker (4)
      • Git (1)
      • Java (9)
      • Javascript (2)
      • JPA (5)
      • MongoDB (1)
      • Network (3)
      • Nginx (1)
      • Projects (1)
      • React (1)
      • Spring (11)
      • SQLD (2)
      • TIL (1)
      • Operating System (2)
      • 정보처리기사 (2)
      • 홈 서버 (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    컴퓨터구조
    백준
    docker
    JPA
    restAPI
    인터페이스
    파이썬
    알고리즘
    스택
    네트워크
    Stack
    SQLD
    Troubleshooting
    Beakjoon
    자바기초
    spring boot
    자바
    스프링 입문
    python
    Interface
    DATABASE
    Queue
    Java
    스프링 핵심 원리
    운영체제
    DevOps
    자료구조
    Spring
    spring-boot
    정리
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
CHun2
Spring Boot - ResponseEntity 클래스
상단으로

티스토리툴바