[스프링 웹 개발 기초] MVC와 템플릿 엔진

김지수·2023년 8월 13일
0

MVC와 템플릿 엔진

  • MVC와 템플릿 엔진
    • 과거 jsp, php가 소위 말하는 템플릿 엔진
    • html을 서버에서 프로그래밍 해서 동적으로 바꿔서 내려줌
    • 그걸 위해 MVC(model, view, controller)를 사용함

Controller

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

Controller는 서버 비즈니스 로직과 같은 뒷단과 관련된 일만!


View

  • resources/templates/hello-template.html
  <html xmlns:th="http://www.thymeleaf.org">
  <body>
  <p th:text="'hello ' + ${name}">hello! empty</p>
  </body>
</html>

View는 화면과 관련된 일만!


Model

화면에서 필요한 것들을 담아서 화면 쪽에 넘겨줌!

http://localhost:8080/hello-mvc 이렇게 하면 에러 페이지가 뜬다.

http://localhost:8080/hello-mvc?name=spring 로 실행해야 한다.

  1. name=spring! 이 넘어가면 Controller에서 namespring!으로 바뀜

  2. model에 담김

  3. template으로 넘어감

    • src/main/resources/templates/hello-template.html
    <html xmlns:th="http://www.thymeleaf.org">
    <body>
    <p th:text="'hello ' + ${name}">hello! empty</p>
    <!--템플릿 엔진이 동작하면 hello! empty 가 'hello ' + ${name} 으로 치환된다. -->
    </body>
    </html>

    namespring!


    과정 요약

profile
안녕하세요

0개의 댓글