m1ndy5's coding blog

정적 컨텐츠 VS MVC와 템플릿엔진 VS API 본문

백엔드 with java/spring

정적 컨텐츠 VS MVC와 템플릿엔진 VS API

정민됴 2023. 3. 7. 22:25

정적 컨텐츠

  • 파일을 그대로 web browser에 전달해주는 것
  • /resources/static에 html파일을 만들고 그대로 보여주는 것
  • 파일명 그대로 url을 들어오면 됨 ex)주소/hello-static.html
  • 프로그래밍할 수는 없음
  • 처음에 컨트롤러로 들어왔을 때 매칭되는 컨트롤러가 없으면 resources/static에 들어가서 있는 html화면을 띄워줌.

MVC와 템플릿 엔진

  • html을 그냥 주는 것이 아닌 서버에서 프로그래밍 하고 return
  • MVC : Model, View, Controller
  • parameter를 넘길 때 예시
//localhost:8080/hello-mvc?name=
@GetMapping("hell-mvc")
public String helloMvc(@RequestParam("name") String name, Model model){
    model.addAttribute("name", name);
    return "hello-template";
}
  • /resources/templates에서 hello-template.html을 찾아서 연결

API

  • JSON형식으로 데이터만 전달하는 것
  • 서버끼리 통신할 때도 API 사용
@GetMapping("hello-string")
@ResponseBody //꼭 넣어주기!
public String helloString(@RequestParam("name") String name){
    return "hello" + name;
}

객체 return (Json 형식)

@Getter
@Setter
static class Hello {
    private String name;
}
@GetMapping("hello-api")
@ResponseBody
public Hello helloApi(@RequestParam("name") String name){
    Hello hello = new Hello();
    hello.setName(name);
    return hello;
}
  • {”name” : {parameter}} 형식으로 뜨게 됨.
  • @ResponseBody 역할
    • http 통신 프로토콜의 header와 body중 body에 내용을 직접 넣어주겠다라는 의미
    • viewResolver 대신 HttpMessageConverter가 동작
    • 기본 문자처리 : StringHttpMessageConverter
    • 기본 객체처리 : MappingJackson2HttpMessageConverter
    • byte 처리 등등 기타 여러 HttpMessageConverter가 기본으로 등록되어 있음

※ 클라이언트의 HTTP Accept 해더와 서버의 컨트롤러 반환 타입 정보 둘을 조합해서 HttpMessageConverter 가 선택됨 근데 거의 Json씀