프레임워크/Spring-Boot

[Spring-Boot] 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술(2)

benjykim 2021. 2. 14. 12:15
반응형

[Spring-Boot] 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술(2)

  1. 외부 라이브러리

    • 앞에서 언급한 Gradle 혹은 Maven 과 같은 툴들은 모두 의존 관계를 관리해준다.
  2. 뷰 설정

    • resources/staticindex.html 파일 추가

      • 스프링 부트가 제공하는 Welcome Page 기능

        • staticindex.html을 올려두면 Welcome Page 를 볼 수 있다. 다시 말하면, 스프링 부트는 resources/static에서 index.html파일을 검색한 뒤 이를 웹 브라우저에게 그대로 넘겨준다.
  • resources/templatehello.html 파일 추가

    • 템플릿 엔진을 사용하면 프로그래밍을 통해 동적 페이지를 생성(?)가능하다. 즉, 렌더링을 통해 동적으로 여러 데이터를 페이지에 삽입할 수 있다.

    • 동작 과정

      1. 웹 브라우저가 helloController 에게 요청을 넘긴다.

      2. helloController 는 해당 요청을 받고, 해당 요청에 맞는 놈이 있는지 확인한다. GetMapping("hello") 가 있으므로 hello 함수가 실행된다.

        • 소스코드

          @GetMapping("hello")
          public String hello(Model model) {
              model.addAttribute("data", "hello!!");
              return "hello"; // 여기서 "hello"는 'templates/hello.html'을 의미한다.
          }
        • Model 에 "data" 라는 Key 에 "hello!!"라는 Value를 넣어서 리턴한다.

        • return hello"; 를 통해 컨트롤러에서 리턴 값으로 문자를 반환하면 Model이 viewResolver에게 전달되고, viewResolver는 Model과 templates/hello.html을 가지고 렌더링을 한다. 그러고 나서 렌더링한 결과 hello.html을 웹 브라우저에게 전달한다.

  • 참고
    • 스프링 부트 템플릿 엔진 기본 viewName 매핑
    • resources:templates/ + {viewName} + .html
  1. 빌드 및 실행하기
    1. ./gradlew build
    2. cd build/libs
    3. java -jar hello-spring-0.0.1-SNAPSHOT.jar
    4. 실행 확인
반응형