Skip to content

Kotlin과 Ktor로 웹사이트 만들기

코드 예제: tutorial-server-web-application

사용된 플러그인: Static Content스타일시트, 스크립트, 이미지 등과 같은 정적 콘텐츠를 서빙하는 방법을 알아봅니다., Thymeleaf필요한 의존성: io.ktor:ktor-server-thymeleaf

이 튜토리얼에서는 Kotlin과 Ktor, 그리고 Thymeleaf 템플릿을 사용하여 대화형 웹사이트를 구축하는 방법을 알아봅니다.

이전 튜토리얼Kotlin과 Ktor를 사용하여 백엔드 서비스를 구축하는 방법을 배우며, JSON을 생성하는 RESTful API 예제를 다룹니다.에서는 JavaScript로 작성된 싱글 페이지 애플리케이션(SPA)에서 사용할 RESTful 서비스를 만드는 방법을 배웠습니다. 이는 매우 인기 있는 아키텍처이지만 모든 프로젝트에 적합한 것은 아닙니다.

다음과 같이 모든 구현을 서버에 유지하고 클라이언트에는 마크업만 전송하고자 하는 데에는 여러 이유가 있습니다.

  • 단순성 – 단일 코드베이스를 유지 관리할 수 있습니다.
  • 보안성 – 공격자에게 힌트를 줄 수 있는 데이터나 코드가 브라우저에 배치되는 것을 방지합니다.
  • 지원 범위 – 구형 브라우저 및 JavaScript가 비활성화된 환경을 포함하여 가능한 한 폭넓은 클라이언트를 지원할 수 있습니다.

Ktor는 여러 서버 페이지 기술HTML/CSS 또는 JVM 템플릿 엔진으로 구축된 뷰를 사용하는 방법에 대해 알아봅니다.과의 연동을 통해 이러한 방식을 지원합니다.

사전 준비 사항

이 튜토리얼을 독립적으로 진행할 수도 있지만, RESTful API 생성 방법을 다룬 이전 튜토리얼Kotlin과 Ktor를 사용하여 백엔드 서비스를 구축하는 방법을 배우며, JSON을 생성하는 RESTful API 예제를 다룹니다.을 먼저 완료하는 것을 강력히 권장합니다.

IntelliJ IDEA를 설치하는 것을 권장하지만, 원하는 다른 IDE를 사용해도 좋습니다.

Hello Task Manager 웹 애플리케이션

이 튜토리얼에서는 이전 튜토리얼Kotlin과 Ktor를 사용하여 백엔드 서비스를 구축하는 방법을 배우며, JSON을 생성하는 RESTful API 예제를 다룹니다.에서 빌드한 태스크 관리 애플리케이션을 웹 애플리케이션으로 전환해 봅니다. 이를 위해 몇 가지 Ktor 플러그인플러그인은 직렬화, 콘텐츠 인코딩, 압축 등과 같은 공통 기능을 제공합니다.을 사용합니다.

기존 프로젝트에 이러한 플러그인을 직접 추가할 수도 있지만, 새 프로젝트를 생성한 후 이전 튜토리얼의 코드를 점진적으로 가져오는 것이 더 수월합니다. 필요한 코드는 진행 과정에서 모두 제공되므로 이전 프로젝트를 바로 준비해 두지 않아도 됩니다.

플러그인을 포함한 초기 프로젝트 생성

  1. Ktor Project Generator로 이동합니다.

  2. Project artifact 필드에 프로젝트 아티팩트 이름으로 com.example.ktor-task-web-app 을 입력합니다. Ktor Project Generator 프로젝트 아티팩트 이름

  3. 다음 화면에서 Add 버튼을 클릭하여 아래 플러그인을 검색하고 추가합니다.

    • Static Content
    • Thymeleaf

    Ktor Project Generator에서 플러그인 추가 플러그인을 추가하고 나면 프로젝트 설정 아래에 세 개의 플러그인이 모두 나열된 것을 확인할 수 있습니다. Ktor Project Generator 플러그인 목록

  4. Download 버튼을 클릭하여 Ktor 프로젝트를 생성하고 다운로드합니다.

스타터 코드 추가

  1. IntelliJ IDEA 또는 원하는 다른 IDE에서 프로젝트를 엽니다.
  2. src/main/kotlin 으로 이동하여 model 이라는 하위 패키지를 만듭니다.
  3. model 패키지 안에 새 Task.kt 파일을 생성합니다.
  4. Task.kt 파일에 우선순위를 나타내는 enum과 작업을 나타내는 data class를 추가합니다.

    kotlin
    package com.example.model
    
    enum class Priority {
        Low, Medium, High, Vital
    }
    
    data class Task(
        val name: String,
        val description: String,
        val priority: Priority
    )

    이번에도 Task 객체를 생성하여 화면에 표시할 수 있는 형태로 클라이언트에 전송하고자 합니다.

    이전 단계를 되짚어 보면 다음과 같습니다.

    • 요청 처리 및 응답 생성태스크 관리자(Task Manager) 애플리케이션을 빌드하며 Kotlin 및 Ktor를 통한 라우팅, 요청 처리, 파라미터 기초를 학습합니다. 튜토리얼에서는 태스크를 HTML로 변환하는 확장 함수를 직접 작성하여 추가했습니다.
    • RESTful API 생성Kotlin과 Ktor를 사용하여 백엔드 서비스를 구축하는 방법을 배우며, JSON을 생성하는 RESTful API 예제를 다룹니다. 튜토리얼에서는 Task 클래스에 kotlinx.serialization 라이브러리의 Serializable 어노테이션을 지정했습니다.

    이 튜토리얼의 목표는 태스크의 내용을 브라우저에 출력하는 서버 페이지를 만드는 것입니다.

  5. src/main/kotlin 에 있는 Routing.kt 파일을 엽니다.
  6. .configureRouting() 함수에 아래와 같이 /tasks 라우트를 추가합니다.

    kotlin
    fun Application.configureRouting() {
        routing {
            get("/") {
                call.respondText("Hello, World!")
            }
            get("/html-thymeleaf") {
                call.respond(ThymeleafContent("index", mapOf("user" to ThymeleafUser(1, "user1"))))
            }
            // Add this additional route
            get("/tasks") {
                val tasks = listOf(
                    Task("cleaning", "Clean the house", Priority.Low),
                    Task("gardening", "Mow the lawn", Priority.Medium),
                    Task("shopping", "Buy the groceries", Priority.High),
                    Task("painting", "Paint the fence", Priority.Medium)
                )
                call.respond(ThymeleafContent("all-tasks", mapOf("tasks" to tasks)))
            }
            staticResources("/static", "static")
        }
    }

    서버가 /tasks에 대한 요청을 받으면 태스크 목록을 생성한 다음 Thymeleaf 템플릿에 전달합니다. ThymeleafContent 타입은 실행할 템플릿의 이름과 페이지에서 접근할 값들의 테이블(Map)을 매개변수로 받습니다.

  7. src/main/kotlin 에 있는 Thymeleaf.kt 파일을 엽니다.
  8. 다음과 같은 .configureThymeleaf 함수가 표시되어 있어야 합니다.

    kotlin
    fun Application.configureThymeleaf() {
        install(Thymeleaf) {
            setTemplateResolver(ClassLoaderTemplateResolver().apply {
                prefix = "templates/thymeleaf/"
                suffix = ".html"
                characterEncoding = "utf-8"
            })
        }
    }

    Thymeleaf 플러그인 초기화 설정에서 Ktor는 서버 페이지를 찾기 위해 templates/thymeleaf 폴더를 탐색합니다. 정적 콘텐츠와 마찬가지로, 이 폴더는 resources 디렉터리 내에 위치해야 합니다. 또한 파일 접미사로 .html 을 기대합니다.

    이 경우 all-tasks라는 이름은 src/main/resources/templates/thymeleaf/all-tasks.html 경로와 매핑됩니다.

  9. src/main/resources 로 이동하여 새 templates/thymeleaf 디렉터리를 만듭니다.
  10. src/main/resources/templates/thymeleaf 안에 새 all-tasks.html 파일을 생성합니다.
  11. all-tasks.html 파일을 열고 아래 내용을 추가합니다.

    html
    <!DOCTYPE html >
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>All Current Tasks</title>
    </head>
    <body>
    <h1>All Current Tasks</h1>
    <table>
        <thead>
        <tr>
            <th>Name</th><th>Description</th><th>Priority</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="task: ${tasks}">
            <td th:text="${task.name}"></td>
            <td th:text="${task.description}"></td>
            <td th:text="${task.priority}"></td>
        </tr>
        </tbody>
    </table>
    </body>
    </html>
  12. IntelliJ IDEA에서 실행 버튼 (IntelliJ IDEA 실행 아이콘) 을 클릭하여 애플리케이션을 시작합니다.

  13. 브라우저에서 http://0.0.0.0:8080/tasks로 이동합니다. 아래와 같이 모든 현재 작업이 테이블 형식으로 표시됩니다.

    태스크 목록을 표시하는 웹 브라우저 창

    모든 서버 페이지 프레임워크와 마찬가지로, Thymeleaf 템플릿은 정적 콘텐츠(브라우저로 전송됨)와 동적 콘텐츠(서버에서 실행됨)를 혼합하여 사용합니다. Freemarker와 같은 다른 대체 프레임워크를 선택했더라도 약간 다른 구문으로 동일한 기능을 구현할 수 있습니다.

GET 라우트 추가

서버 페이지를 요청하는 과정에 익숙해졌으므로, 이제 이전 튜토리얼의 기능들을 이 프로젝트로 옮겨오는 작업을 계속 진행합니다.

Static Content 플러그인을 포함했기 때문에 Routing.kt 파일에 다음 코드가 포함되어 있을 것입니다.

kotlin
staticResources("/static", "static")

이는 예를 들어 /static/index.html에 대한 요청이 발생하면 다음 경로에서 콘텐츠를 제공함을 의미합니다.

src/main/resources/static/index.html

이 파일은 이미 생성된 프로젝트의 일부로 포함되어 있으므로, 앞으로 추가할 기능들을 위한 홈 페이지로 활용할 수 있습니다.

index 페이지 재사용

  1. src/main/resources/static 내에 있는 index.html 파일을 열고 해당 내용을 아래 구현으로 바꿉니다.

    html
    <html>
    <head>
    </head>
    <body>
    <h1>Task Manager Web Application</h1>
    <div>
        <h3><a href="/tasks">View all the tasks</a></h3>
    </div>
    <div>
        <h3>View tasks by priority</h3>
        <form method="get" action="/tasks/byPriority">
            <select name="priority">
                <option name="Low">Low</option>
                <option name="Medium">Medium</option>
                <option name="High">High</option>
                <option name="Vital">Vital</option>
            </select>
            <input type="submit">
        </form>
    </div>
    <div>
        <h3>View a task by name</h3>
        <form method="get" action="/tasks/byName">
            <input type="text" name="name" width="10">
            <input type="submit">
        </form>
    </div>
    <div>
        <h3>Create or edit a task</h3>
        <form method="post" action="/tasks">
            <div>
                <label for="name">Name: </label>
                <input type="text" id="name" name="name" size="10">
            </div>
            <div>
                <label for="description">Description: </label>
                <input type="text" id="description"
                       name="description" size="20">
            </div>
            <div>
                <label for="priority">Priority: </label>
                <select id="priority" name="priority">
                    <option name="Low">Low</option>
                    <option name="Medium">Medium</option>
                    <option name="High">High</option>
                    <option name="Vital">Vital</option>
                </select>
            </div>
            <input type="submit">
        </form>
    </div>
    </body>
    </html>
  2. IntelliJ IDEA에서 재실행 버튼(IntelliJ IDEA 재실행 아이콘)을 클릭하여 애플리케이션을 다시 시작합니다.

  3. 브라우저에서 http://localhost:8080/static/index.html로 이동합니다. 링크 버튼과 작업을 조회, 필터링, 생성할 수 있는 세 개의 HTML 폼이 표시됩니다.

    HTML 폼을 표시하는 웹 브라우저

    name 또는 priority별로 태스크를 필터링할 때는 GET 요청을 통해 HTML 폼을 제출한다는 점에 유의하세요. 즉, 매개변수가 URL 뒤의 쿼리 스트링(query string)에 추가됩니다.

    예를 들어 Medium 우선순위의 작업을 검색하는 경우, 서버로 전송되는 요청은 다음과 같습니다.

    http://localhost:8080/tasks/byPriority?priority=Medium

태스크 리포지토리 재사용

    태스크용 리포지토리는 이전 튜토리얼의 코드와 완전히 동일하게 유지할 수 있습니다.

    model 패키지 안에 새 TaskRepository.kt 파일을 만들고 아래 코드를 추가합니다.

    kotlin
    package com.example.model
    
    object TaskRepository {
        private val tasks = mutableListOf(
            Task("cleaning", "Clean the house", Priority.Low),
            Task("gardening", "Mow the lawn", Priority.Medium),
            Task("shopping", "Buy the groceries", Priority.High),
            Task("painting", "Paint the fence", Priority.Medium)
        )
    
        fun allTasks(): List<Task> = tasks
    
        fun tasksByPriority(priority: Priority) = tasks.filter {
            it.priority == priority
        }
    
        fun taskByName(name: String) = tasks.find {
            it.name.equals(name, ignoreCase = true)
        }
    
        fun addTask(task: Task) {
            if (taskByName(task.name) != null) {
                throw IllegalStateException("Cannot duplicate task names!")
            }
            tasks.add(task)
        }
    }

GET 요청을 위한 라우트 재사용

    리포지토리를 만들었으므로 이제 GET 요청을 처리할 라우트를 구현할 수 있습니다.

  1. src/main/kotlin 에 있는 Routing.kt 파일로 이동합니다.
  2. 현재의 .configureRouting() 버전을 아래 구현으로 대체합니다.

    kotlin
    fun Application.configureRouting() {
        routing {
            get("/") {
                call.respondText("Hello, World!")
            }
            get("/html-thymeleaf") {
                call.respond(ThymeleafContent("index", mapOf("user" to ThymeleafUser(1, "user1"))))
            }
            staticResources("/static", "static")
    
            route("/tasks") {
                get {
                    val tasks = TaskRepository.allTasks()
                    call.respond(
                        ThymeleafContent("all-tasks", mapOf("tasks" to tasks))
                    )
                }
                get("/byName") {
                    val name = call.request.queryParameters["name"]
                    if (name == null) {
                        call.respond(HttpStatusCode.BadRequest)
                        return@get
                    }
                    val task = TaskRepository.taskByName(name)
                    if (task == null) {
                        call.respond(HttpStatusCode.NotFound)
                        return@get
                    }
                    call.respond(
                        ThymeleafContent("single-task", mapOf("task" to task))
                    )
                }
                get("/byPriority") {
                    val priorityAsText = call.request.queryParameters["priority"]
                    if (priorityAsText == null) {
                        call.respond(HttpStatusCode.BadRequest)
                        return@get
                    }
                    try {
                        val priority = Priority.valueOf(priorityAsText)
                        val tasks = TaskRepository.tasksByPriority(priority)
    
    
                        if (tasks.isEmpty()) {
                            call.respond(HttpStatusCode.NotFound)
                            return@get
                        }
                        val data = mapOf(
                            "priority" to priority,
                            "tasks" to tasks
                        )
                        call.respond(ThymeleafContent("tasks-by-priority", data))
                    } catch (ex: IllegalArgumentException) {
                        call.respond(HttpStatusCode.BadRequest)
                    }
                }
            }
        }
    }

    위 코드는 다음과 같이 요약할 수 있습니다.

    • /tasks로의 GET 요청 시, 서버는 리포지토리에서 모든 작업을 가져와 all-tasks 템플릿을 사용하여 브라우저로 전송될 다음 뷰를 생성합니다.
    • /tasks/byName으로의 GET 요청 시, 서버는 queryString에서 name 매개변수를 가져와 일치하는 태스크를 찾고, single-task 템플릿을 사용하여 브라우저로 전송될 다음 뷰를 생성합니다.
    • /tasks/byPriority로의 GET 요청 시, 서버는 queryString에서 priority 매개변수를 가져와 일치하는 태스크들을 찾고, tasks-by-priority 템플릿을 사용하여 브라우저로 전송될 다음 뷰를 생성합니다.

    이 모든 것이 정상 작동하려면 추가 템플릿을 생성해야 합니다.

  3. src/main/resources/templates/thymeleaf 로 이동하여 새 single-task.html 파일을 만듭니다.
  4. single-task.html 파일을 열고 다음 내용을 추가합니다.

    html
    <!DOCTYPE html >
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>All Current Tasks</title>
    </head>
    <body>
    <h1>The Selected Task</h1>
    <table>
        <tbody>
        <tr>
            <th>Name</th>
            <td th:text="${task.name}"></td>
        </tr>
        <tr>
            <th>Description</th>
            <td th:text="${task.description}"></td>
        </tr>
        <tr>
            <th>Priority</th>
            <td th:text="${task.priority}"></td>
        </tr>
        </tbody>
    </table>
    </body>
    </html>
  5. 동일한 폴더에 tasks-by-priority.html 이라는 새 파일을 만듭니다.

  6. tasks-by-priority.html 파일을 열고 다음 내용을 추가합니다.

    html
    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Tasks By Priority </title>
    </head>
    <body>
    <h1>Tasks With Priority <span th:text="${priority}"></span></h1>
    <table>
        <thead>
        <tr>
            <th>Name</th>
            <th>Description</th>
            <th>Priority</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="task: ${tasks}">
            <td th:text="${task.name}"></td>
            <td th:text="${task.description}"></td>
            <td th:text="${task.priority}"></td>
        </tr>
        </tbody>
    </table>
    </body>
    </html>

POST 요청 지원 추가

다음으로, 아래 작업을 수행할 수 있도록 /tasks에 POST 요청 핸들러를 추가합니다.

  • 폼 매개변수에서 정보를 추출합니다.
  • 리포지토리를 사용하여 새 태스크를 추가합니다.
  • all-tasks 템플릿을 재사용하여 태스크 목록을 표시합니다.
  1. src/main/kotlin 에 있는 Routing.kt 파일로 이동합니다.
  2. .configureRouting() 메서드 내에 다음 post 요청 라우트를 추가합니다.

    kotlin
    post {
        val formContent = call.receiveParameters()
        val params = Triple(
            formContent["name"] ?: "",
            formContent["description"] ?: "",
            formContent["priority"] ?: ""
        )
        if (params.toList().any { it.isEmpty() }) {
            call.respond(HttpStatusCode.BadRequest)
            return@post
        }
        try {
            val priority = Priority.valueOf(params.third)
            TaskRepository.addTask(
                Task(
                    params.first,
                    params.second,
                    priority
                )
            )
            val tasks = TaskRepository.allTasks()
            call.respond(
                ThymeleafContent("all-tasks", mapOf("tasks" to tasks))
            )
        } catch (ex: IllegalArgumentException) {
            call.respond(HttpStatusCode.BadRequest)
        } catch (ex: IllegalStateException) {
            call.respond(HttpStatusCode.BadRequest)
        }
    }
  3. IntelliJ IDEA에서 재실행 버튼(IntelliJ IDEA 재실행 아이콘)을 클릭하여 애플리케이션을 다시 시작합니다.

  4. 브라우저에서 http://0.0.0.0:8080/static/index.html로 이동합니다.
  5. Create or edit a task 폼에 새 태스크 세부 정보를 입력합니다.

    HTML 폼을 표시하는 웹 브라우저
  6. Submit 버튼을 클릭하여 폼을 제출합니다. 그러면 전체 태스크 목록에 새 태스크가 추가되어 표시되는 것을 확인할 수 있습니다.

    태스크 목록을 표시하는 웹 브라우저

다음 단계

축하합니다! Task Manager를 웹 애플리케이션으로 성공적으로 다시 구축하고 Thymeleaf 템플릿을 사용하는 방법을 배웠습니다.

WebSocket을 다루는 방법을 알아보려면 다음 튜토리얼WebSocket을 활용하여 콘텐츠를 주고받는 방법을 알아봅니다.로 진행하세요.