使用 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 插件插件提供常见功能性,例如序列化、内容编码、压缩等。。
虽然您可以手动将这些插件添加到现有项目中,但生成一个新项目并逐步合并上一个教程中的代码会更加简单。我们将在整个过程中提供所有必要的代码,因此您手头无需准备之前的项目。
使用插件创建初始项目
在 Project artifact 字段中,输入 com.example.ktor-task-web-app 作为项目工件的名称。

在下一个屏幕中,搜索并通过点击 Add 按钮添加以下插件:
- Static Content
- Thymeleaf
添加插件后,您将在项目设置下方看到列出的全部三个插件。 
点击 Download 按钮生成并下载您的 Ktor 项目。
添加初始代码
- 在 IntelliJ IDEA 或您自选的其他 IDE 中打开项目。
- 导航至 src/main/kotlin 并创建一个名为 model 的子包。
- 在 model 包内,新建一个 Task.kt 文件。
在 Task.kt 文件中,添加一个用于表示优先级的
enum以及一个用于表示任务的data class:kotlinpackage 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类。
而在本例中,目标是创建一个服务器页面,将任务的内容写入浏览器中。
- 打开 src/main/kotlin 中的 Routing.kt 文件。
在
.configureRouting()函数中,为/tasks添加一条路由,如下所示:kotlinfun 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类型接收要触发的模板名称以及可在页面上访问的值表格。- 打开 src/main/kotlin 中的 Thymeleaf.kt 文件。
您应该会看到以下
.configureThymeleaf函数:kotlinfun 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- 导航至 src/main/resources 并新建一个 templates/thymeleaf 目录。
- 在 src/main/resources/templates/thymeleaf 中,新建一个 all-tasks.html 文件。
打开 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>在 IntelliJ IDEA 中,点击运行按钮 (
) 以启动应用程序。
在浏览器中访问 http://0.0.0.0:8080/tasks。您应该会看到表格中显示的所有当前任务,如下所示:

与所有服务器页面框架一样,Thymeleaf 模板将静态内容(发送到浏览器)与动态内容(在服务器上执行)混合在一起。如果您选择了其他框架,例如 Freemarker,您可以使用略有不同的语法提供相同的功能。
添加 GET 路由
现在您已熟悉请求服务器页面的过程,接下来继续将上一个教程中的功能迁移到本教程中。
由于您引入了 Static Content 插件,Routing.kt 文件中将包含以下代码:
staticResources("/static", "static") 这意味着,例如对 /static/index.html 的请求将由以下路径的内容提供服务:
src/main/resources/static/index.html由于该文件已经是生成项目的一部分,因此您可以将其用作要添加功能的主页。
复用 index 页面
打开 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>在 IntelliJ IDEA 中,点击重新运行按钮(
)以重启应用程序。
在浏览器中访问 http://localhost:8080/static/index.html。您应该会看到一个链接按钮和三个 HTML 表单,可用于查看、筛选和创建任务:

请注意,当您按
name或priority筛选任务时,您是在通过 GET 请求提交 HTML 表单。这意味着形参会被添加到 URL 后面的查询字符串中。例如,如果您搜索优先级为
Medium的任务,发送到服务器的请求如下所示:http://localhost:8080/tasks/byPriority?priority=Medium
复用任务仓库
任务仓库可以与上一个教程中的保持完全相同。
在 model 包内新建一个 TaskRepository.kt 文件,并添加以下代码:
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 请求的路由
- 导航至 src/main/kotlin 中的 Routing.kt 文件。
将当前版本的
.configureRouting()替换为以下实现:kotlinfun 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 模板生成发送到浏览器的下一个视图。
要使这一切正常工作,您需要添加额外的模板。
- 在对
- 导航至 src/main/resources/templates/thymeleaf 并新建一个 single-task.html 文件。
打开 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>在同一文件夹中,新建一个名为 tasks-by-priority.html 的文件。
打开 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>
创建仓库后,即可实现用于 GET 请求的路由。
添加对 POST 请求的支持
接下来,您将向 /tasks 添加一个 POST 请求处理程序以执行以下操作:
- 从表单形参中提取信息。
- 使用仓库添加新任务。
- 通过复用 all-tasks 模板来显示任务。
- 导航至 src/main/kotlin 中的 Routing.kt 文件。
在
.configureRouting()方法中添加以下post请求路由:kotlinpost { 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) } }在 IntelliJ IDEA 中,点击重新运行按钮(
)以重启应用程序。
- 在浏览器中访问 http://0.0.0.0:8080/static/index.html。
在 Create or edit a task 表单中输入新任务的详细信息。

点击 Submit 按钮提交表单。 随后您将在所有任务的列表中看到新添加的任务:

后续步骤
祝贺您!您现已完成将 Task Manager 重建为 Web 应用程序的过程,并学会了如何使用 Thymeleaf 模板。
请继续学习下一个教程了解如何利用 WebSockets 发送和接收内容。,以了解如何使用 WebSockets。
