스터디/Spring

Spring 스터디 - 2

라퐁 2025. 2. 10. 00:00

정적 컨텐츠

정적 컨텐츠(Static Content)는 기본적으로 /static 경로 아래에 있는 파일을 그대로 보여준다.

 

index.html을 호출하면 먼저 Controller에서 매핑된 게 있는지 확인하고, 없으면 /static에서 확인한다.
정정 컨텐츠는 프로그램(계산한 값을 가진다거나 등) 할 수 없다.

MVC와 템플릿 엔진

MVC는 Model, View, Controller의 각 앞 글자를 딴 것이다.

  • Controller
//Controller
@Controller
public class HelloController {

    @GetMapping("hello")
    public String hello(Model model) {
        model.addAttribute("data", "hello");
        return "hello";
    }
}
  • View
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Hello</title>
</head>
<body>
<p th:text="'안녕하세요. ' + ${data}">안녕하세요. 손님</p>
</body>
</html>

View는 보여지는 역할이며, Model이나 Controller는 내부에서 비즈니스 로직을 처리하는 역할이다.

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

/hello-mvc?name=hong을 호출하면 Controller에서 hello-mvc와 매핑된 걸 찾고, 입력 받은 name 파라미터를 받아서 hello-template로 View에전달하면, View는 ${name}을 파라미터로 치환한다. 여기서 템플릿 엔진인 Thymeleaf가 템플릿 양식과 데이터를 결합한 최종 HTML을 생성해서 클라이언트에 전달하는 방식이다.

API

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

@ResponseBody 어노테이션을 사용하면 위 템플릿 엔진과 다르게 HTTP Body에 JSON 형식의 데이터가 그대로 전달된다. /hello-api?name=hong을 호출하면 Controller에서 hello-api와 매핑된 걸 찾고, @ResponseBody를 확인하면 viewResolver 대신 HttpMessageConverter가 동작하면서 JSON 형식으로 전달하는 것이다.