
: Spring Framework에서 HTTP 요청에 대한 응답을 캡슐화하여 제공하는 객체.
<T>를 사용하여 응답 바디에 원하는 데이터를 담을 수 있다.@PostMapping("/example")
public ResponseEntity<String> example() {
String responseBody = "Hello, world!";
return new ResponseEntity<>(responseBody, HttpStatus.OK);
}
: 위 코드에서는 ResponseEntity<String>을 통해 문자열 응답과 함께 HTTP 상태 코드 200(OK)을 반환한다.
@PostMapping("/example")
public ResponseEntity<ExampleResponseDto> example() {
ExampleResponseDto responseDto = new ExampleResponseDto("Hello, world!", 123);
return new ResponseEntity<>(responseDto, HttpStatus.OK);
}
// ExampleResponseDto 클래스
public class ExampleResponseDto {
private String message;
private int id;
public ExampleResponseDto(String message, int id) {
this.message = message;
this.id = id;
}
// Getters and Setters
}
import axios from 'axios';
axios.post('/example')
.then(response => {
console.log(response.status); // 200
console.log(response.data); // { message: 'Hello, world!', id: 123 }
})
.catch(error => {
console.error(error);
});
{
"data": {
"message": "Hello, world!",
"id": 123
},
"status": 200,
"statusText": "OK",
"headers": {
"content-type": "application/json"
},
"config": { ... },
"request": { ... }
}
: ResponseEntity를 사용하는 가장 큰 이유는 HTTP 응답에 대한 세밀한 제어를 제공하기 때문이다. 이를 통해 상태 코드, 헤더, 바디를 모두 명확하게 설정할 수 있다.
: ResponseEntity를 사용하여 HTTP 상태 코드를 명시적으로 사용할 수 있는 것이 가장 큰 이유라고 볼 수 있다.
return new ResponseEntity<>("해당 리소스를 찾을 수 없습니다.", HttpStatus.NOT_FOUND);
: 이는 응답 body에 사용자 정의 메세지를 담았고, 상태 코드를 404로 지정했다.
ResponseEntity란?
: Spring에서 HTTP 응답을 캡슐화하는 객체로, 상태 코드, 헤더, 바디를 포함하여 클라이언트에 응답을 보냄.
특징