본문 바로가기

Spring

Spring Boot - ResponseEntity 클래스

반응형

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