본문 바로가기
Java Web/Spring Boot

[Spring Boot] ResponseEntity

by 스응 2023. 4. 11.
728x90
728x90

ResponseEntity<자료형>

  - 결과 데이터와 HTTP 상태 코드를 직접 제어할 수 있는 클래스

  - ResponseEntity를 사용한 일관된 형식을 만들어서 return함으로써, API 개발이 편리해짐

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// User : DTO
 
@PostMapping("/post")
public ResponseEntity<User> post(@RequestBody User user) {
 
    // HTTP 메세지 바디의 데이터를 user object로 그대로 반환
    // 상태 코드를 마음대로 변경할 수 있음
    return ResponseEntity.status(HttpStatus.OK).body(user);
    // HttpStatus.OK는 아래와 같이 축약 가능
    // return ResponseEntity.ok(user);
}
 
----------------------------------------
 
@PutMapping("/put2")
public ResponseEntity<String> put2(@RequestBody User user) {
    
    // HTTP 메시지의 헤더에 담길 MIME 타입 지정
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.TEXT_PLAIN); // 문자열로 지정할 때보다 실수 위험이 적음
    
    // HttpStatus.CREATED (201) : 생성, 수정
    // HttpStatus.OK (200) : 성공
    return new ResponseEntity<>(user.toString(), headers, HttpStatus.CREATED);
}
cs

 

  - 상태 코드 : https://young0105.tistory.com/185

 

#  ResponseEntity<?>

  - 와일드 카드 ?를 사용함

      → 상황에 따라 다른 타입을 리턴해야 할 때 사용할 수 있음

 

320x100
반응형

댓글