[BACK-END]/[SPRING]

정적 컨텐츠 / MVC / API 방식 기초

지기음 2022. 12. 5. 09:28

spring은 웹 개발할 때 3가지 방식을 이용할 수 있다. 그중 MVC방식과 API방식은 아주 잘 사용되는 방식이므로 동작 방법을 잘 알아놔야한다. 

 

정적컨텐츠

간단한 방법이다. html 파일을 찾아 그대로 출력해주는 방식이다. (정은 움직이지 않는다는 뜻이다.)

hello-static.html파일을 만들었다고 생각해보자

  1. 브라우저에서 8080:hello-static.html 넘어옴
  2. 스프링 컨테이너 안에 있는 hello-static 관련 컨트롤러를 찾아봄(없음)
  3. 없다면 resources/static/hello-static.html있는지 찾아봄 → 있다면 출력

이 방식으로 동작한다. 단순히 html을 출력한다면 spring의 장점을 활용할 수 없는 방식이다. 

 

웹 MVC와 템플릿 엔진 

view단과 controller 단이 분리되어 작동하는 방식이다. 

 @GetMapping("hello-mvc")
    public String helloMvc(@RequestParam("name") String name,Model model){
        model.addAttribute("name",name);
        return "hello-temlpate";
    }

변수를 받아와서 출력해보자 

받아온 변수를 출력하는 html은 

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'안녕하세요.' + ${name}">안녕하세요 손님</p>
</body>
</html>

name변수를 받아 출력시킬예정이다. 이렇게 된다면

?name 은 get 방식

spring의 변수를 받아서 출력할 수 있게 된다.

 

API방식

api방식은 HttpMessageConverter 를통하여 작동한다. 

StringConveter 방식은 http body에 직접 넣어주는 방식이다. 

@GetMapping("hello-string")
    @ResponseBody   //http body부분에 직접 값을 넣어주겠다.
    public String helloString(@RequestParam("name") String name){
        return "hello" + name ; //
    }

출력은 MVC방식이랑 동일하게 출력이 된다. 

 

jsonConverter 방식은 객체가 넘어왔을 떄 동작하는 방식이다. 

@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;
        }
    }

이 때 객체를 넘겨주게 되면 spring은 자동으로 jsonConveter를 이용하게 되고 이에따라 출력되는 화면은 JSON방식으로 출력되게 된다.

이 세가지 방법의 동작원리를 잘 익혀두자

'[BACK-END] > [SPRING]' 카테고리의 다른 글

Spring bean  (0) 2022.12.14
Spring 백엔드 기초 중 기초 [회원관리]-(2)  (0) 2022.12.07
Spring 백엔드 기초 중 기초 [회원관리]-(1)  (0) 2022.12.07
IntelliJ 단축키  (0) 2022.12.05
SPRING 시작  (0) 2022.12.01