ApiResponse란 어떤 클래스든지 받을 수 있도록 하게 만드는 기능이다.
쉽게 말하여 Get 방식을 사용할 때 succes, errormessage, data의 여부를 Response 할때 쉽게 알 수 있도록
표시하는 기능 인것 같다.
사용법을 알아 보도록 하자.
여러 군데의 디렉토리에서 공용으로 사용할 수 있도록 'common'이라는 디렉토리를 만들어서
ApiResponse.java를 생성한다.
package kr.ac.daegu.springbootapi.common;
import lombok.Getter;
@Getter
public class ApiResponse<T> { // wild card : 어떤 클래스던 받을 수 있다! 를 선언
private final boolean success;
private String errorMessage = null;
private T data;
public ApiResponse(boolean success, T data) {
this.success = success;
this.data = data;
}
public ApiResponse(boolean success, String errorMessage) {
this.success = success;
this.errorMessage = errorMessage;
}
public ApiResponse(boolean success, String errorMessage, T data) {
this.success = success;
this.errorMessage = errorMessage;
this.data = data;
}
}
그다음 Board 디렉토리 안의 클래스에 적용 시키기 위하여 boardcontroller.java의 코드를 수정한다.
다음은 기존의 list를 받아오고 반환시키는 구문이다.
위의 구문을
ApiResponse로 list를 받아 오도록 수정시킨다.
반환도 ApiResponse로 하고 list와 함께 반환.
Postman으로 결과를 살펴보도록 하자
정상적으로 send가 되었으며 body의 첫부분에 success,errorMessage,data가 나오는것을 볼 수 있다!
'Spring boot' 카테고리의 다른 글
Spring boot (post body 변형) (0) | 2021.09.30 |
---|---|
Spring boot (board 테이블 insert) (0) | 2021.09.30 |
Springboot (auto_increment) (0) | 2021.09.30 |
Spring boot (insert test) (0) | 2021.09.29 |
Stringboot (board 테이블 연결) (0) | 2021.09.29 |