정적 컨텐츠

Untitled

웹 브라우저 실행 → 내장 톰켓 서버가 요청을 받음 → hello-static 컨트롤러가 있는지 확인 → 컨트롤러 없으므로 resources에서 html 파일을 찾아서 응답으로 넘김.

MVC와 템플릿 엔진

view: 화면을 그리는데 집중.

model, controller: 비지니스 로직을 처리, 벡엔드 처리하는데 집중.

Untitled

웹 브라우저 → 내장 톰캣 서버 → 스프링 컨테이너 : [Controller: template 반환] → [viewResolver: Thymeleaf 템플릿 엔진 처리] → HTML 변환 후 웹 브라우저에 반환.

HelloController

@Controller
public class HelloController {
    @GetMapping("hello")    //template 방식. viewResolver를 통해 html로 변환 후 반환
    public String hello(Model model){
        model.addAttribute("data","hello!!");
        return "hello";
    }

    @GetMapping("hello-mvc")
    public String helloMvc(@RequestParam("name") String name, Model model){
        model.addAttribute("name",name);  //url 요청에 담긴 name을 모델에 담아서 보냄.
        return "hello-template";
    }
}

hello-template

<!DOCTYPE html>
<html xmlns:th="<http://www.thymeleaf.org>">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>

API

@Controller
public class HelloController {
    
    @GetMapping("hello-string")
    @ResponseBody   //http 응답에 데이터를 그대로 넘김. MessageConverter-StringConverter
    public String helloString(@RequestParam("name") String name){
        return "hello " + name;
    }

    @GetMapping("hello-api")
    @ResponseBody   //객체를 넘겨 받을 경우 json 형태로 응답을 넘김. MessageConverter-JsonConverter
    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;
        }
    }
}

Untitled

@ResponseBody

HTTP body의 문자 내용을 직접 반환. 객체일 경우 Json으로 변환 후 반환.

viewResolver 대신 HttpMessageConverter가 동작한다.