1. ResponseEntity
'ResponseEntity'는 상태 코드, 헤더, 본문을 포함한 전체 HTTP 응답을 나타내는 Spring Framework 클래스이다.
유연한 방식으로 응답을 작성하고 반환하는 데 사용되므로 상태 코드, 헤더 및 본문 내용을 명시적으로 설정할 수 있다.
@Builder
@Getter
public class CommonResponse<T> {
private Integer statusCode;
private String msg;
private Object data;
}
@PostMapping
public ResponseEntity<CommonResponse<CommentResponseDto>> createComment(@PathVariable Long scheduleId, @Valid @RequestBody CommentRequestDto requestDto,
ServletRequest request) {
User user = (User) request.getAttribute("user");
Comment comment = service.save(scheduleId, requestDto, user);
CommentResponseDto responseDto = new CommentResponseDto(comment);
return ResponseEntity.ok().body(CommonResponse.<CommentResponseDto>builder()
.statusCode(HttpStatus.OK.value())
.msg("생성이 완료되었습니다.")
.data(responseDto)
.build());
}
- ResponseEntity.ok() : 'ResponseEntity.status(HttpStatus.OK)'의 약어로 Http 상태코드를 200 OK로 설정한다.
- .body() : CommonResponse 객체에 대한 응답 본문을 설정하는데 사용된다.
* 스프링에서 공통 Response를 처리할때 ResponseBodyAdvice를 사용하서 처리한다는 사실을 알았다.
'TIL' 카테고리의 다른 글
240604 TIL (0) | 2024.06.05 |
---|---|
240603 TIL : Spring MVC (0) | 2024.06.03 |
240530 TIL (0) | 2024.05.31 |
240529 TIL (0) | 2024.05.29 |
240528 TIL (0) | 2024.05.29 |