使用 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。
Hello 任務管理器 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 按鈕以提交表單。 隨後您將看到新任務顯示在所有任務的清單中:

後續步驟
恭喜!您現在已完成將任務管理器重新建置為 Web 應用程式,並學習了如何使用 Thymeleaf 範本。
請繼續閱讀下一個教學了解如何利用 WebSockets 的強大功能來傳送與接收內容。,以了解如何使用 WebSocket。
