Springboot3 HashMap ResponseEntity 사용 응답 결과 메세지 만들기

`SpringBoot3`에서 결과메세지 표현할 때
HashMap과 ResponseEntity를 사용하면, 유연한 결과메세지를 만들 수 있다.
`HashMap`은 `key-value 형태`의 데이터구조이며, Json 형태로의 변환 또한 수월하다.
`ResponseEntity`는 HTTP 응답을 `body, header, Status`를 설정한다.
이 2가지를 사용하면 SpringBoot3에서 Rest API 사용시 유연하게 결과메세지를 만들 수 있다.
이후 공통메세지 클래스 형태로 만들어 사용할 수도 있다.

Response Message
ResponseEntity + HashMap

Creating a result message
Using Springboot3 HashMap ResponseEntity
/ Springboot3 HashMap ResponseEntity 사용 응답 결과 메세지 만들기

`Rest API`를 만들 때 중요한 것 중 하나는 
요청에 대한 결과메세지를 편하게 확인하기 위한 
데이터 구조를 만드는 것일 것이다.
처음부터 클래스( Class )형태로 만들어도 상관없지만, 
불편한 느낌이 있다면 `HashMap`형태로 먼저 결과메세지 구조를 만들 수 있다.

`HashMap`은 Key와 Value를 쌍으로 데이터 구조를 만드는 것으로 Json 형태와 비슷하다.
Json과 차이가 있다면,
`HashMap은 객체(Object)`이고, `Json은 문자열(Text)`란 점이다.
`HashMap`과 비교되는 것이 `HashTable`이 있다.
이 둘의 차이점은 스레드 안전성에 있지만, 자세한 건 넘어가자.
Key-Value Pair 형식의 Object 사용에 있어 
HashTable 보다는 `HashMap 사용을 권장`하고 있다.

데이터 구조를 만들었다면 결과메세지를 전달해야 한다.
SpringBoot3에서 결과메세지를 전달할 때 사용하는 것이 `ResponseEntity`이다.
ResponseEntity를 굳이 사용하지 않아도 되지만,
`Body, Header, Http Status`상태까지 전달하고 싶다면
`ResponseEntity`를 사용하는 것이 수월하다.
솔직히, 이런 상세한 정보를 Rese API 결과메세지로 전달해 주면 
개발자 입장에서 편한 건 본인이다.
( 솔직히, 내가 개발하기 편하게 만들어 두면, 다른 사람도 같이 편해지는 듯 하다. )

하나씩 진행해 보자.

SpringBoot3 프로젝트 생성하기

HashMap과 ResponseEntity를 사용해 요청에 대한 결과메세지를 만들기 위해
먼저 프로젝트를 만들어야 한다.
테스트이기 때문에 대충 하나 만들어 두도록 하자.
추후 사용할 곳이 있다면 그 때 코드를 복사하기 붙여넣기하여 사용하면 된다.
SpringBoot3 프로젝트를 만들기 위한 나름의 구체적인 내용은 아래를 참고해 본다.

HashMap 사용 방법
/ Key-Value Pair 

`HashMap`은 `key-value Pair` 컬렉션 형태의 데이터 구조를 만든다.
만들어진 구조화된 데이터는 `람다식`을 사용해 가공할 수도 있고,
Json 형태로 변경하여 문자열 기반의 데이터 가공을 할 수도 있다.

일단 HashMap의 간단한 사용법을 보자.
아래는 HashMap을 객체를 생성하고, 인스턴스화하는 코드이다.

/* HashMap Instance */
HashMap<String, Object> map = new HashMap<>();
map.put( key, value );

아래의 코드는 위의 `HashMap` 기본 코드를 이용하여 
여자 아이돌 그룹을 `Key-Value Pair` 형태로 데이터 구조를 만든 것이며,
결과메세지 부분의 data 부분에 사용할 것이다.

/* HashMap Example */
HashMap<String, Object> map = new HashMap<>();
map.put( "aespa", "카리나, 지젤, 윈터, 닝닝");
map.put( "lesserafim", "김채원, 사쿠라, 허윤진, 카즈하, 홍은채");
map.put( "itzy", "예지, 리아, 류진, 채령, 유나");
map.put( "ive", "안유진, 가을, 레이, 장원영, 리즈, 이서");

코드의 Key는 그룹명이고, Value는 멤버 이름을 나열하였다.
이제 위의 데이터를 ResponseEntity를 사용해 
`Rest API`의 결과메세지로 사용할 것이다.

ResponseEntity 사용 방법
/ Return new ResponseEntity( 메세지객체, [헤더객체], 상태코드)

`ResponseEntity`는 SpringBoot3에서 응답 또는 결과메세지를 만들어준다.
RepnoseEntity는 `Body, Heder, Status`를 설정할 수 있다.
RestAPI를 만들 때 상세한 결과메세지를 만들고,
응답결과를 자세하게 전달할 수 있다.
아래는 간단한 사용법을 보여준다.

return new ResponseEntity<>( 메세지객체, 상태코드 );
return new ResponseEntity<>( 메세지객체, 헤더객체, 상태코드 );
return ResponseEntity .ok() .headers( 헤더객체 ) .body( 메세지객체 );

방법은 여러가지가 있긴 하지만, 편한 방법으로 사용하면 된다.
SpringBoot3에서 Rest API 를 사용할 경우 결과 반환 방법은 다음과 같다.

@GetMapping( 요청 URL )
public ResponseEntity< 메세지객체 자료형 > 메서드명() { }

코드 만들기

간단한 컨트롤러를 만들고 실행해 보자.
만들어진 코드는 간단한다.
SpringBoot3에서 Rest API를 사용하기 위한 `Controller`를 만들고
응답형태는 `ResponseEntity`를 사용한다.
그리고, 결과메세지는 `HashMap`으로 전송한다.

package com.test.api.project.ztest;

import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController
@RequiredArgsConstructor
public class ZTest01RestController {

    @GetMapping("/test/api/response-entity")
    public ResponseEntity<HashMap<String, Object>> ResponseEntityMain() {

        HttpHeaders headers = new HttpHeaders();
        headers.add("X-Custom-Message", "처리 완료");
        headers.add("X-App-Version", "1.0.0");

        HashMap<String, Object> returnMessage = new HashMap<String, Object>();
        returnMessage.put("HttpStatus", HttpStatus.OK);
        returnMessage.put("HttpHeaders", headers);
        returnMessage.put("HttpBody", "Message");

        return new ResponseEntity<>(returnMessage, HttpStatus.OK);

//        return new ResponseEntity<>("헤더 포함 응답", headers, HttpStatus.OK);

//        return ResponseEntity
//                .ok()
//                .headers(headers)
//                .body("헤더 포함 응답");

    }
}

ResponseEntity를 사용하는 return 형태는 3가지 모두 사용 가능하다.
자신에게 편한 것 사용하면 된다.

테스트하기

위의 코드를 테스트해 보도록 하자.
@RestController 어노테이션을 사용하여 Rest API 호출을 위한 컨트롤러를 만들었다.

요청 URL은 `http://localhost:8080/test/api/response-entity`이다.
HashMap은 Key-Value Pair 형태의 객체를 저장한다.

ResponseEntity에 필요한 HttpStatus, HttpHeader, HttpBody를 
Key로 설정하고, Value를 객체로 설정하였다.

HashMap이 ResponseEntity에 설정되고, 응답메시지를 만들면서
자연스럽게 Json 문자열 형태로 변환되는 것을 볼 수 있다.

Json 객체와 HashMap 둘 다 Key-Value Pair 형태이기 때문.

ResponseEntity, HashMap 사용
결과메세지 API 테스트

코드에서 지정한 HashMap 그대로 
Json 문자열로 결과메세지가 만들어진 것을 볼 수 있다.
프로젝트를 새로 만들고 Rest API 만들 때 유연하게 사용할 수 있다.
규격화가 된다면 그 때 응답 결과메세지 클래스를 만들어 사용하면 된다.

코드 수정 후 테스트하기

이제 위에서 HashMap으로 만들어진 아이돌 그룹 목록을
응답 결과 메세지에 추가해 본 후,
Rest API 요청을 하여 테스트를 해 보도록 한다.
아래는 전체 코드를 보여준다.

package com.test.api.project.ztest;

import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController
@RequiredArgsConstructor
public class ZTest01RestController {

    @GetMapping("/test/api/response-entity")
    public ResponseEntity<HashMap<String, Object>> ResponseEntityMain() {

        /* HTTP Status 설정 */
        HttpStatus httpStatusCode = HttpStatus.OK;

        /* HTTP Header 설정 */
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("X-Custom-Message", "처리 완료");
        httpHeaders.add("X-App-Version", "1.0.0");

        /* HTTP Body 설정 */
        HashMap<String, Object> dtoListIdol = new HashMap<>();
        dtoListIdol.put( "aespa", "카리나, 지젤, 윈터, 닝닝");
        dtoListIdol.put( "lesserafim", "김채원, 사쿠라, 허윤진, 카즈하, 홍은채");
        dtoListIdol.put( "itzy", "예지, 리아, 류진, 채령, 유나");
        dtoListIdol.put( "ive", "안유진, 가을, 레이, 장원영, 리즈, 이서");

        /* Response Message 설정 */
        HashMap<String, Object> httpBody = new HashMap<String, Object>();
        httpBody.put("HttpStatus", httpStatusCode);
        httpBody.put("HttpHeader", httpHeaders);
        httpBody.put("data", dtoListIdol);

        /* Return Response-Message */
        return new ResponseEntity<>(
                httpBody,
                httpStatusCode
        );

    }
}

뭔가 번거롭게 보이지만, 설정값을 만들고, 적용하는 방법만 알면 된다.
추후 경우에 따라 조건문을 활용해 Http 상태와 결과값을 변경하면 
좀 더 자유로운 메세지를 만들 수 있다.
이제 위의 코드에 대한 Rest API 결과를 확인해 본다.

ResponseEntity, HashMap data

HashMap으로 만들어진 아이돌 그룹 목록을 
ResponseEntity에 적용하여 Rest API에 적용하였다.
그럴듯한 RestAPI 응답 결과메세지가 만들어졌다.


댓글

이 블로그의 인기 게시물

AI 종류와 특징 / 모두 고유한 특징이 있다.

레이싱 마스터 PC 버전 에뮬레이터 설치 방법

MySQL CREATE TABLE 테이블 생성 기본 템플릿 쿼리 만들기