- Kotlin is a general-purpose programming language that is static typed, supports OOP and FP, and was developed by JetBrains. Ktor is a web framework for Kotlin that supports asynchronous servers and clients.
- Ktor allows building web applications using routing to define endpoints, application calls to handle requests and responses, and features like HTML rendering, JSON serialization, and database access using Exposed.
- A full-stack Kotlin web application example was demonstrated using Ktor, Exposed ORM, and a MySQL database to build both a web UI and RESTful API for a todo list application.
24. HTML DSL
—
get("/") {
val tasks = mutableListOf<String>()
for (i in 0..9) {
tasks.add("Task $i")
}
call.respondHtml {
head {
title { +"ToDo List" }
}
body {
h1 { +"ToDo List" }
p { +"a simple ToDo application" }
ul {
tasks.map {
li { +it }
}
}
}
}
}
29. JSON respond
—
data class TaskRespond (
val title: String,
val completed: Boolean = false
)
get("/api/v1/tasks") {
val task = TaskRespond("Task 1”)
call.respond(
mapOf("task" to task)
)
}
30. JSON respond
—
get("/api/v1/tasks") {
val tasks = mutableListOf<TaskRespond>()
for (i in 1..10) {
tasks.add(TaskRespond("Task $i"))
}
call.respond(
mapOf("tasks" to tasks)
)
}
32. Exposed DB
MySQL Connector
—
// build.gradle
dependencies {
//...
implementation "org.jetbrains.exposed:exposed:$ver"
implementation "mysql:mysql-connector-java:$ver"
}
33. Table
—
object Tasks: IntIdTable() {
val title = varchar("title", 255)
val completed = bool("completed")
val createdAt = datetime("created_at")
val updatedAt = datetime("updated_at")
}
34. Entity
—
class Task(id: EntityID<Int>) : IntEntity(id) {
companion object : IntEntityClass<Task>(Tasks)
var title by Tasks.title
var completed by Tasks.completed
var createdAt by Tasks.createdAt
var updatedAt by Tasks.updatedAt
}