[Spring] ResponseEntity

노유성·2023년 7월 21일
0
post-thumbnail

ResponseEntity는 HttpEntity를 상속받은 class이다.

생성자

	/**
	 * Create a {@code ResponseEntity} with a status code only.
	 * @param status the status code
	 */
	public ResponseEntity(HttpStatusCode status) {
		this(null, null, status);
	}

	/**
	 * Create a {@code ResponseEntity} with a body and status code.
	 * @param body the entity body
	 * @param status the status code
	 */
	public ResponseEntity(@Nullable T body, HttpStatusCode status) {
		this(body, null, status);
	}

	/**
	 * Create a {@code ResponseEntity} with headers and a status code.
	 * @param headers the entity headers
	 * @param status the status code
	 */
	public ResponseEntity(MultiValueMap<String, String> headers, HttpStatusCode status) {
		this(null, headers, status);
	}

	/**
	 * Create a {@code ResponseEntity} with a body, headers, and a status code.
	 * @param body the entity body
	 * @param headers the entity headers
	 * @param status the status code
	 */
	public ResponseEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers, HttpStatusCode status) {
		this(body, headers, (Object) status);
	}

	/**
	 * Create a {@code ResponseEntity} with a body, headers, and a raw status code.
	 * @param body the entity body
	 * @param headers the entity headers
	 * @param rawStatus the status code value
	 * @since 5.3.2
	 */
	public ResponseEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers, int rawStatus) {
		this(body, headers, (Object) rawStatus);
	}

	/**
	 * Private constructor.
	 */
	private ResponseEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers, Object status) {
		super(body, headers);
		Assert.notNull(status, "HttpStatusCode must not be null");
		this.status = status;
	}

위와 같은 생성자들이 있다. 응답 코드의 값은 고정적으로 들어가고 generic타입을 지정해서 body 부분의 값을 추가할지, header에 들어갈 값을 추가할지, 전부다 추가할지 결정할 수 있다.

이렇게 만들어진 값은 @ResponseBody annotation에 의해서 직렬화가 된 이후에 클라이언트에게 전달된다.

예제

로그인을 시도하면 로그인 정보를

{
    "status": 200,
    "message": "로그인 성공",
    "data": {
       "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWRIjoib3VyLXNvcHQbpXkxZgFXHw"
    }
}

이렇게 json형태로 반환하는 예제를 만들어보자

entity

@Data
public class LoginReq {
    private String name;
    private String password;
}

로그인 정보를 담는 entity이다.

StatusCode

public class StatusCode {
    public static final int OK = 200;
    public static final int CREATED = 201;
    public static final int NO_CONTENT = 204;
    public static final int BAD_REQUEST =  400;
    public static final int UNAUTHORIZED = 401;
    public static final int FORBIDDEN = 403;
    public static final int NOT_FOUND = 404;
    public static final int INTERNAL_SERVER_ERROR = 500;
    public static final int SERVICE_UNAVAILABLE = 503;
    public static final int DB_ERROR = 600;
}

client에게 전달할 내용중 status 부분에 해당하는 파트이다.

ResponseMessage

public class ResponseMessage {
    public static final String LOGIN_SUCCESS = "로그인 성공";
    public static final String LOGIN_FAIL = "로그인 실패";
    public static final String READ_USER = "회원 정보 조회 성공";
    public static final String NOT_FOUND_USER = "회원을 찾을 수 없습니다.";
    public static final String CREATED_USER = "회원 가입 성공";
    public static final String UPDATE_USER = "회원 정보 수정 성공";
    public static final String DELETE_USER = "회원 탈퇴 성공";
    public static final String INTERNAL_SERVER_ERROR = "서버 내부 에러";
    public static final String DB_ERROR = "데이터베이스 에러";
}

client에게 전달할 내용중 message에 해당하는 부분이다.

DefaultEntity

@Data @AllArgsConstructor @Builder
public class DefaultRes<T> {
    private int statusCode;
    private String responseMessage;
    private T data;

    public DefaultRes(final int statusCode, final String responseMessage) {
        this.statusCode = statusCode;
        this.responseMessage = responseMessage;
        this.data = null;
    }
    public static<T> DefaultRes<T> res(final int statusCode, final String responseMessage) {
        return res(statusCode, responseMessage, null);
    }

    public static<T> DefaultRes<T> res(final int statusCode, final String responseMessage, final T t) {
        return DefaultRes.<T>builder()
                .data(t)
                .statusCode(statusCode)
                .responseMessage(responseMessage)
                .build();
    }
}

로그인 entity를 이용해서 client가 받을 json형태로 포멧해주는 class이다.

Controller

@Controller
@RequestMapping("/test")
public class TestController {

    @PostMapping()
    public ResponseEntity login(@RequestBody LoginReq loginReq) {
        return new ResponseEntity(DefaultRes.res(StatusCode.OK, ResponseMessage.LOGIN_SUCCESS, loginReq), HttpStatus.OK);
    }
}

/test로 client가 post 요청을 보내면은 그에 대해 응답을 하는 controller이다.

ResponseEntity 생성자에서 Body와 httpStatus만 채워서 ResponseEntity 객체를 생성한다. 그리고 이를 client에게 반환하면은

아래와 같이 결과를 받을 수 있다.

profile
풀스택개발자가되고싶습니다:)

0개의 댓글