[Kotlin] 코틀린 스프링 부트, 간단한 컨트롤러 생성 및 페이지 띄우기(#2) (feat. mustache)

코틀린 스프링부트, 컨트롤러 생성 후 페이지 접속해보기

- TestController.kt 생성

- pom.xml에 mustache 디펜던시 추가.

 

1. 현재 프로젝트 구조

 

- main/resources/templates 디렉토리 아래애 footer, header, index 머스터치 파일 생성

 

pom.xml

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-mustache</artifactId>
</dependency>

Mustache 디펜던시 추가. -> mvn clean -> mvn install

 

TestController.kt

package com.example.demokotlin.test

import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.ui.set
import org.springframework.web.bind.annotation.GetMapping

@Controller
class TestController {

    @GetMapping("/test")
    fun test(model: Model): String {
        model["title"] = "testTitle" //model.addAttribute("title", "test")
        return "index"
    }

}

- TestController는 @Controller 어노테이션으로 빈 등록은 Java 개발할때와 똑같음.

- "index"라는 String을 리턴하므로 뷰 리졸버는 index.mustache를 찾아감. -> 기존 스프링 개발과 같은 모습.

- model["title"] 은 흔히 알고 있는 Model 객체에 "title" 속성으로 값을 넘기는 것과 같음.

- 비슷한 방식으로 Service, Repository를 등록하는 방법도 기존 스프링과 같은 것이라고 예측 가능함.

 

header.mustache

<html>
<head>
    <title>{{title}}</title>
</head>
<body>

- {{title}}은 mustache 템플릿 엔진 문법으로 model에서 넘긴 title이라는 키에 해당하는 값을 꽂아줌.

 

footer.mustache

</body>
</html>

- 얘는 단지 닫아주는 역할임.

 

index.mustache

{{> header}}
<h1>{{title}}</h1>
{{> footer}}

- {{> header}}과 {{> footer}}는 마찬가지로 mustache 템플릿 엔진 문법으로 header.mustache 에 있는 내용을 include 하는 것이라고 생각하면 됨.

- 위에서 먼저 보아서 아시겠지만 header는 index의 안으로 include 되기 때문에 최종 html 문서는 모든 mustache를 합치고 model에서 꺼내온 값을 매핑한 후, html로 최종 변환되어 브라우저에 출력되는 것을 알 수 있음.

 

main 함수 실행

 

http://localhost:8080/index 접속

- 탭 제목이 testTitle인 것 확인!

- h1태그의 제목이 testTitle인 것 확인!

- 참고로 포트가 8081인 것은 겹치는 포트가 있어서... 끄면 안되는 포트라 8081로 뒀습니다...( 이것은 application.properties에 "server.port = 8081"로 설정하시면 됩니다. )

댓글

Designed by JB FACTORY