HTML
With Ktor HTML DSL, you can respond to a client with HTML blocks.
HTML DSL
The HTML DSL integrates kotlinx.html so you can build responses as HTML blocks. You can write HTML in Kotlin, interpolate variables, and compose complex layouts with templates.
Add the ktor-server-html-builder artifact:
dependencies:
- $ktor.server.htmlBuilderUpdate Routing.kt:
fun Application.configureRouting() {
routing {
get("/") {
call.respondHtml {
body { h1 { +"Hello World!" } }
}
}
}
}Task Manager Application
You’ll incrementally build a Task Manager with:
- Viewing all tasks in an HTML table.
- Filtering tasks by priority and name.
- Adding tasks via an HTML form.
Display static HTML content
Add a route that returns static HTML.
Modify Application.configureRouting() to a new route for the URL /task and the GET request type:
import kotlinx.html.*
fun Application.configureRouting() {
routing {
get("/") {
call.respondText("Hello David!")
}
get("/task") {
call.respondHtml {
body {
h1 {
+"Tasks"
}
ul {
li {
+"Create project documentation"
}
li {
+"Implement user authentication"
}
}
}
}
}
}
}A GET request is the most basic type of request in HTTP. It is triggered when the user types into the browser’s address bar or clicks a normal HTML link.
For now, you’re only returning static content. To notify the client that you will send HTML, you must set the HTTP Content Type header to “text/html.”
Navigate to http://localhost:8080/task in your browser.
You should see the list of tasks:
Tasks
- Create project documentation
- Implement user authentication
Implement a Task Model
-
Inside
srccreate a new subpackage namedmodel. -
Inside the model directory create a new file
Task.kt. -
Open the
Task.ktfile and add the following enum to represent priorities and a class to represent tasks:kotlin src/model/Task.kt package org.jetbrains.amper.ktor.model enum class Priority { Low, Medium, High, Vital } data class Task( val name: String, val description: String, val priority: Priority )
Estàs llegint una vista prèvia.
Inicia sessió per llegir l'article complet. Qualsevol compte obre 4 articles gratuïts al mes; l'alumnat i el professorat llegeixen les pàgines del seu curs sense límit.
Inicia sessió