[2-2] MVC와 템플릿 엔진

ohun·2022년 5월 21일
0

Spring 입문

목록 보기
5/16
post-thumbnail

MVC : Model, View, Controller

  • View 는 화면을 그리는 데 집중!
  • Controller 등은 비즈니스 로직에 집중!

Controller (HelloController.java)

@Controller
  public class HelloController {

			...

      @GetMapping("hello-mvc")
      public String helloMvc(@RequestParam("name") String name, Model model) {
          model.addAttribute("name", name);
          return "hello-template";
      }
}
  • @RequestParam 으로 외부(URL 파라미터)에서 데이터(name) 가져오기.
  • model 로 넘겨주기 위해서 model 도 선언
  • model 에 파라미터로 받아온 name 넣기.
  • hello-template 으로 넘기기(return)

View (hello-template.html)

<html xmlns:th="http://www.thymeleaf.org">
  <body>
  <p th:text="'hello ' + ${name}">hello! empty</p>
  </body>
</html>
  • $ 표시는 model 의 키 값을 가져온다.
  • View 작성 후 localhost:8080/hello-mvc 페이지로 이동하면 Whitelabel Error Page 가 뜬다!
  • Why? 파라미터(name)를 빼먹어서!
  • 다시 localhost:8080/hello-mvc?name=spring! 페이지로 이동하면 spring! 이라고 뜨는 화면이 정상적으로 나온다.
profile
공부 중입니다.

0개의 댓글