Skip to content

使用 Ktor 在 Kotlin 中创建网站

代码示例: tutorial-server-web-application

使用的插件:Static Content了解如何提供静态内容,例如样式表、脚本、图像等。、 Thymeleaf所需依赖项: io.ktor:ktor-server-thymeleaf

在本教程中,您将学习如何使用 Ktor 和 Thymeleaf 模板在 Kotlin 中构建交互式网站。

在上一个教程了解如何使用 Kotlin 和 Ktor 构建后端服务,并包含一个生成 JSON 文件的 RESTful API 示例。中,您学习了如何创建一个 RESTful 服务,供使用 JavaScript 编写的单页面应用程序 (SPA) 调用。虽然这是一种非常流行的架构,但它并不适合所有项目。

在很多情况下,您可能希望将所有实现保留在服务器端,而仅将标记发送给客户端,原因如下:

  • 简单性 – 维护单一代码库。
  • 安全性 – 避免将可能为攻击者提供深入洞察的数据或代码放置在浏览器端。
  • 可支持性 – 允许尽可能广泛的客户端进行访问,包括旧版浏览器以及禁用了 JavaScript 的浏览器。

Ktor 通过与多种服务器页面技术了解如何使用 HTML/CSS 或 JVM 模板引擎构建的视图。集成来支持这种方式。

前提条件

您可以单独完成本教程,但我们强烈建议您先完成上一篇教程了解如何使用 Kotlin 和 Ktor 构建后端服务,并包含一个生成 JSON 文件的 RESTful API 示例。,以了解如何创建 RESTful API。

我们建议您安装 IntelliJ IDEA,但您也可以使用自选的其他 IDE。

Task Manager Web 应用程序入门

在本教程中,您将把在上一个教程了解如何使用 Kotlin 和 Ktor 构建后端服务,并包含一个生成 JSON 文件的 RESTful API 示例。中构建的任务管理应用程序转换为 Web 应用程序。为此,您将使用几个 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 对象并以可显示的形式发送给客户端。

    您可能还记得:

    • 在处理请求并生成响应通过构建一个任务管理器应用程序,学习在 Kotlin 中使用 Ktor 处理路由、请求和形参的基础知识。教程中,您添加了手写的扩展函数来将任务转换为 HTML。
    • 在创建 RESTful API了解如何使用 Kotlin 和 Ktor 构建后端服务,并包含一个生成 JSON 文件的 RESTful API 示例。教程中,您使用 kotlinx.serialization 库中的 Serializable 类型注解了 Task 类。

    而在本例中,目标是创建一个服务器页面,将任务的内容写入浏览器中。

  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 类型接收要触发的模板名称以及可在页面上访问的值表格。

  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。您应该会看到表格中显示的所有当前任务,如下所示:

    显示任务列表的 Web 浏览器窗口

    与所有服务器页面框架一样,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 表单的 Web 浏览器

    请注意,当您按 name 或 priority 筛选任务时,您是在通过 GET 请求提交 HTML 表单。这意味着形参会被添加到 URL 后面的查询字符串中。

    例如,如果您搜索优先级为 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 表单的 Web 浏览器
  6. 点击 Submit 按钮提交表单。 随后您将在所有任务的列表中看到新添加的任务:

    显示任务列表的 Web 浏览器

后续步骤

祝贺您!您现已完成将 Task Manager 重建为 Web 应用程序的过程,并学会了如何使用 Thymeleaf 模板。

请继续学习下一个教程了解如何利用 WebSockets 发送和接收内容。,以了解如何使用 WebSockets。