spring API

Seungsoo Lee·2022년 11월 6일
0

web

목록 보기
11/13

앞서서 MVC에서는 클라이언트에서 get요청이 들어오면 controller를 통해 get 메소드 함수에서 데이터들을 model을 통해 저장을한다. 그리고 그 함수는 template 이름을 리턴하는데 view-resolver 알아서 view(html template)를 찾아서 클라이언트로 보여지게된다. 한마디로 MVC는 요청을 받아서 html을 웹브라우저에 보낸다고 생각하면 된다.

그러나 데이터만 필요한 경우 html을 보내는것은 비효율적일 수 있다. 따라서 json 형식의 데이터만 보내줄 수 도 있는데, 이것이 API인것이다.

package hello.hellospring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloController {

    @GetMapping("hello-string")
    @ResponseBody
    public String helloString(@RequestParam("name") String name) {
        return "hello" + name;
    }

    @GetMapping("hello-api")
    @ResponseBody
    public Hello helloApi(@RequestParam("name") String name) {
        Hello hello = new Hello();
        hello.setName(name);
        return hello;
    }

    static class Hello {
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}

  • http 프로토콜

    • 우리가 클라이언트와 서버간의 통신을 하기위해서는 http 프로토콜을 지켜야한다.

    • 종류로는 response / request가 있다.

      • 클라이언트가 httpRequest(요청)을 하면 서버는 그에 맞는 httpRequeset(응답)을 해주는 형식이다.
    • http request 구조

        // start line
        POST /payment-sync HTTP/1.1
      
        // headers
        Accept: application/json
        Accept-Encoding: gzip, deflate
        Connection: keep-alive
        Content-Length: 83
        Content-Type: application/json
        Host: intropython.com
        User-Agent: HTTPie/0.9.3
      
        // body (JSON 형식)
        {
            "id": "test0101",
            "email": "test0101@gmail.com",
            "address": "google"
        }
      • start(status) line, headers, body 이런식으로 세부분으로 구조가 나뉜다.
      • 여기서 body가 중요한데, 서버와 클라이언트의 http 통신에서 요청과 응답을 보낼때, 필요한 데이터를 담아서 보내는 공간이 body이다.
      • 이때 body에 들어가는 데이터 형식에는 json이 많이 사용된다. (xml형식도 있다)
  • @ResponseBody
    • 이 annotation은 http의 body에 정보를 전달해주는 역할을 한다.
    • 정확하게는 MessageConverter를 이용하여 데이터 변환과정을 거치게 되는데, 예를 들어 요청된 데이터를 처리한후 서버에서 클라이언트로 다시 응답 데이터 responseBody를 보낼 때도 Java Object에서 JSON 또는 XML 같은 형식으로의 변환이 필요하다. 이러한 과정을 @ResponseBody가 처리를 해준다.
      • @ResponseBody는 자바 객체를 HttpResponse의 body인 responseBody의 내용으로 매핑하는 역할을 한다.
      • return type에 맞는 MessageConverter를 통해 return 하는 객체를 해당 타입으로 변환해서 클라이언트로 전달하게 된다

참고
https://wildeveloperetrain.tistory.com/144

0개의 댓글