이번 강의는 2번을 들었는데도 이해가 잘 되지 않아 쓰면서 정리하는 게 나을 것 같다.

 

주요 과제는 server와 client간의 연결을 구현하는 것이다.

 

@RestController
@RequestMapping("/api/client")
public class ApiController {

    private final RestTemplateService restTemplateService;

    public ApiController(RestTemplateService restTemplateService) {
        this.restTemplateService = restTemplateService;
    }

    @GetMapping("/hello")
    public UserResponse getHello(){
       return restTemplateService.hello();
    }


}

우선 ApiController를 작성하였다. Talend API Tester에 GET메서드로 http://localhost:8080/api/client/hello를 보내게 되면 restTemplateService.hello()가 실행되는데 RestTemplateService클래스는 다음과 같이 선언된다.

 

@Service
public class RestTemplateService {


    //http://localhost/api/server/hello
    //response
    public UserResponse hello(){

       URI uri = UriComponentsBuilder
               .fromUriString("http://localhost:9090")
               .path("/api/server/hello")
               .queryParam("name", "steve")
               .queryParam("age", 10)
               .encode()
               .build().toUri();

        System.out.println(uri.toString());

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<UserResponse> result = restTemplate.getForEntity(uri, UserResponse.class);
        //uri : http://localhost:9090/api/server/hello?name=steve&age=10

        System.out.println(result.getStatusCode());
        System.out.println(result.getHeaders());
        System.out.println(result.getBody());

        return result.getBody();
    }

hello 메서드는 우선 uri를 생성하는데 UriComponentBuilder를 통해 뒤에 입력되는 여러 가지 파라미터들을 통해 http://localhost:9090/api/sever/hello?name=steve&age=10인 URI를 생성할 것이다. 

 

새로 생성한 객체 result에는 어떤 값들이 들어갈까. 아래를 보면 status, header, body를 출력하는 것을 알 수 있다. 

restTemplate.getForEntity(uri, UserResponse.class) 는 result객체를 생성할 때 3가지의 값을 넣어주는구나~라고 생각하고 넘어가자.

 

그럼 이제 client와 통신하는 서버를 생성을 해줘야한다.

@Slf4j
@RestController
@RequestMapping("/api/server")
public class ServerApiController {



    @GetMapping("/hello")
    public User hello(@RequestParam String name, @RequestParam int age){

        User user = new User();
        user.setName(name);
        user.setAge(age);
        return user;
    }


}

우리는 클라이언트와 서버를 연결하여 서버로부터의 응답(reponse)을 출력하고 싶다. 위에서부터 하나씩 살펴보면 이전에 클라이언트에서 URI를 http://localhost:9090/api/sever/hello?name=steve&age=10로 생성했다 여기에 name과 age값이 차례로 들어가 있는데 이 값들이 서버에 생성한 User의 name과 age를 set해준다. 

 

우리가 이전에 클라이언트에서 출력하려 한 3개의 값이 있다. status, header, body 이 3개의 값들은 Talend API Tester를 통해 URI가 전달될 때 client의 콘솔에 우리가 생성한 URI와 값들이 출력되도록 설정하였는데 그 결과는 다음과 같다.

순서대로 URI, status, header, body이다. 우린 여기서 body의 name과 age에 주목을 해야 하는데 생각해보면 우리는 URI를 설정해준 적은 있지만 UserReponse객체(client내부에 선언해둔)의 name과 age에 직접 값을 초기화 해준 적이 없다. 그럼 어떻게 저 값들이 출력된 것일까?

 

ResponseEntity<UserResponse> result = restTemplate.getForEntity(uri, UserResponse.class);

result객체는 restTemplate.getForEntity(uri, UserResponse.class)의 값을 통해 생성되는데 도대체 이 안에 무슨 값이 있는지 자세히 살펴보니

 

잘 보이지는 않지만 순서대로 보면 status, body, header의 값이 순서대로 출력된다. 결국 result는 서버가 요청(request)을 받고 다시 client에게 보내준 응답(response)의 내용들을 포함하는 객체인 것이다.

 

이렇게 요청에 의한 응답을 확인할 수 있었다.

'웹 개발 일기 > Spring' 카테고리의 다른 글

JUnit을 Spring에서 활용하여 테스트 진행하기  (0) 2021.06.22
JUnit  (0) 2021.06.22
Filter / Interceptor  (0) 2021.06.17
예외 처리  (0) 2021.06.15
AOP(Aspect Oriented Programming)  (0) 2021.06.15

+ Recent posts