개발 낙서장

[TIL] 내일배움캠프 22일차 - Response Entity - 본문

Java/Sparta

[TIL] 내일배움캠프 22일차 - Response Entity -

권승준 2024. 1. 24. 20:25

오늘의 학습 키워드📚

Response Entity

  • Spring Framework에서 제공하는 클래스 중 HTTP 요청(Request) 또는 응답(Response)에 해당하는 HttpHeader와 HttpBody를 포함하는 HttpEntity라는 클래스가 존재한다. 이 HttpEntity를 상속한 클래스가 ResponseEntity 클래스이다.
    (RequestEntity도 존재한다.)
  • Response Entity는 HttpStatus, HttpHeader, HttpBody를 포함한다.
  • HTTP 응답에 따른 제어가 필요할 때 Response Entity 클래스를 사용한다.

사용법은 간단(?)하다. 응답 성공(200)을 의미하는 ok에 데이터를 담아 return 해주면 된다.

    @GetMapping("/{id}")
    public ResponseEntity<ScheduleResponseDto> getScheduleById(@PathVariable Long id) {
        return ResponseEntity.ok(scheduleService.getScheduleById(id));
    }

근데 body 말고 응답 상태라던지 응답 상태 코드를 담아주지 않았는데 확인할 수 있는 방법이 있다.

    @GetMapping("/{id}")
    public ResponseEntity<?> getScheduleById(@PathVariable Long id) {
        return ResponseEntity.ok(HttpStatus.OK);
    }

이런 식으로 Http 응답 상태에 대한 정보를 담아서 처리할 수도 있다.

상태는 정말 다양하므로 상황에 맞게 사용하면 될 것 같다.

    @GetMapping("/{id}")
    public ResponseEntity<?> getScheduleById(@PathVariable Long id) {
        return ResponseEntity.ok(HttpStatus.OK.value());
    }

또한 상태의 value()로 상태 코드를 확인할 수도 있다.

그럼 이걸 처리할 때는 상태 코드, 메시지, 데이터를 모두 담고 싶다면 새로 클래스를 만들어 거기에 담아 반환해주면 된다.

@Getter
@Setter
@Builder
public class ResponseMessage<T> {
    int httpCode;
    String msg;
    T data;
}

상태 코드, 메세지, 반환할 데이터를 담은 ResponseMessage 클래스를 만들었다.
빌더 패턴을 통해 상태 코드와 메세지, 데이터를 담아 생성해주어 body에 담아 반환해주면 된다.

    @GetMapping("/{id}")
    public ResponseEntity<ResponseMessage<?>> getScheduleById(@PathVariable Long id) {
        return ResponseEntity.ok(ResponseMessage.builder()
                        .msg(id + " 유저 탐색 완료")
                        .httpCode(HttpStatus.OK.value())
                        .data(scheduleService.getScheduleById(id))
                .build());
    }

상태 코드, 메세지, 데이터까지 이쁘게 잘 담아서 반환된다.
만약 실패할 수도 있으니 그땐 예외를 던져 Controller에서 잡아주면 된다.

    public ScheduleResponseDto getScheduleById(Long id) {
        Schedule schedule = scheduleRepository.findById(id).orElseThrow( () ->
                new IllegalArgumentException("선택한 스케줄이 존재하지 않습니다.")
        );

        return new ScheduleResponseDto(schedule);
    }

Service에서 데이터를 올바르게 반환받지 못했을 경우 예외를 던지도록 했다.

    @GetMapping("/{id}")
    public ResponseEntity<ResponseMessage<?>> getScheduleById(@PathVariable Long id) {
        ScheduleResponseDto dto;

        try {
            dto = scheduleService.getScheduleById(id);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().
                    body(ResponseMessage.builder()
                            .msg(id + " 유저 탐색 실패")
                            .httpCode(HttpStatus.BAD_REQUEST.value())
                            .data(null)
                            .build());
        }

        return ResponseEntity.ok(ResponseMessage.builder()
                .msg(id + " 유저 탐색 완료")
                .httpCode(HttpStatus.OK.value())
                .data(dto)
                .build());
    }

기능이 복잡해지면 예외를 나눠서 해결할 수 있을 것 같다.

        // 스케줄을 조회합니다.
        function showSchedule() {
            modalToggle(true);

            $.ajax({
                type: 'GET',
                url: `/api/schedules/${currentId}`,
                success: function (response) {
                    let message = response['data'];
                    let id = message['id'];
                    let name = message['name'];
                    let content = message['content'];
                    let username = message['username'];
                    let modifiedAt = message['modifiedAt'];
                    setModalValue(id, name, content, username);
                }
            })
        }

JQuery에서 데이터를 받으려면 해당 클래스의 데이터가 담긴 필드 명으로 받아오면 된다.


오늘의 회고💬

그냥 데이터를 반환하면 되는 줄 알았는데 이렇게 상태까지 담아서 반환하는게 처음엔 이해가 되지 않았지만 차근차근 검색해보고 해설 코드를 보면서 접근해서 어찌저찌 이해는 한 것 같다.
근데 어려워서 집중은 쉽지 않았다😥

 

내일의 계획📜

Spring 숙련 주차 강의를 내일부터는 진짜 들어야지!!!!

Comments