Guides: How to create a plain website using ktor

In this guide you will learn how to create an HTML Website using Ktor.We are going to create a simple website with HTML rendered at the back-end with users, a login form,and keeping a persistent session.

To achieve this, we are going to use the Routing, StatusPages, Authentication, Sessions, StaticContent,FreeMarker, and HTML DSL features.

Table of contents:

Setting up the project

The first step is to set up a project. You can follow the Quick Start guide, or use the following form to create one:

the pre-configured generator form))

Simple routing

First of all, we are going to use the routing feature. This feature is part of the Ktor’s core, so you won’t needto include any additional artifacts.

This feature is installed automatically when using the routing { } block.

Let’s start creating a simple GET route that responds with ‘OK’:

  1. fun Application.module() {
  2. routing {
  3. get("/") {
  4. call.respondText("OK")
  5. }
  6. }
  7. }

Serving HTML with FreeMarker

Apache FreeMarker is a template engine for the JVM, and thus you can use it with Kotlin.There is a Ktor feature supporting it.

For now, we are going to store the templates embedded as part of the resources in a templates folder.

Create a file called resources/templates/index.ftl and put in the following content to create a simple HTML list:

  1. <#-- @ftlvariable name="data" type="com.example.IndexData" -->
  2. <html>
  3. <body>
  4. <ul>
  5. <#list data.items as item>
  6. <li>${item}</li>
  7. </#list>
  8. </ul>
  9. </body>
  10. </html>

IntelliJ IDEA Ultimate has FreeMarker support with autocompletion and variable hinting.

Now, let’s install the FreeMarker feature and then create a route serving this template and passing a set of values to it:

  1. data class IndexData(val items: List<Int>)
  2. fun Application.module() {
  3. install(FreeMarker) {
  4. templateLoader = ClassTemplateLoader(this::class.java.classLoader, "templates")
  5. }
  6. routing {
  7. get("/html-freemarker") {
  8. call.respond(FreeMarkerContent("index.ftl", mapOf("data" to IndexData(listOf(1, 2, 3))), ""))
  9. }
  10. }
  11. }

Now you can run the server and open a browser pointing to http://127.0.0.1:8080/html-freemarker to see the results:

Website - 图1

Nice!

Serving static files: styles, scripts, images…

In addition to templates, you will want to serve static content.Static content will serve faster, and is compatible with other features like Partial Content that allowsyou to resume downloads or partially download files.

For now, we are going to serve a simple styles.css file to apply styles to our simple page.

Serving static files doesn’t require installing any features, but it is a plain Route handler.To serve static files at the /static url, from /resources/static, you would write the following code:

  1. routing {
  2. // ...
  3. static("/static") {
  4. resources("static")
  5. }
  6. }

Now let’s create the resources/static/styles.css file with the following content:

  1. body {
  2. background: #B9D8FF;
  3. }

In addition to this, we will have to update our template to include the style.css file:

  1. <#-- @ftlvariable name="data" type="com.example.IndexData" -->
  2. <html>
  3. <head>
  4. <link rel="stylesheet" href="/static/styles.css">
  5. </head>
  6. <body>
  7. <!-- ... -->
  8. </body>
  9. </html>

And the result:

Website - 图2

Now we have a colorful website from 1990!

Static files are not only text files! Try to add an image (what about a fancy animated blinking gif file? 👩🏻‍🎨) to the static folder, and include a <img src="…"> tag to the HTML template.

Enabling partial content: large files and videos

Though not really needed for this specific case, if you enable partial content support, people will be ableto resume larger static files on connections with frequent problems, or allow seeking support whenserving and watching videos.

Enabling partial content is straightforward:

  1. install(PartialContent) {
  2. }

Creating a form

Now we are going to create a fake login form. To make it simple, we are going to accept users with the same password,and we are not going to implement a registration form.

Create a resources/templates/login.ftl:

  1. <html>
  2. <head>
  3. <link rel="stylesheet" href="/static/styles.css">
  4. </head>
  5. <body>
  6. <#if error??>
  7. <p style="color:red;">${error}</p>
  8. </#if>
  9. <form action="/login" method="post" enctype="application/x-www-form-urlencoded">
  10. <div>User:</div>
  11. <div><input type="text" name="username" /></div>
  12. <div>Password:</div>
  13. <div><input type="password" name="password" /></div>
  14. <div><input type="submit" value="Login" /></div>
  15. </form>
  16. </body>
  17. </html>

In addition to the template, we need to add some logic to it. In this case we are going to handle GET and POST methods in different blocks of code:

  1. route("/login") {
  2. get {
  3. call.respond(FreeMarkerContent("login.ftl", null))
  4. }
  5. post {
  6. val post = call.receiveParameters()
  7. if (post["username"] != null && post["username"] == post["password"]) {
  8. call.respondText("OK")
  9. } else {
  10. call.respond(FreeMarkerContent("login.ftl", mapOf("error" to "Invalid login")))
  11. }
  12. }
  13. }

As we said, we are accepting username with the same password, but we are not accepting null values.If the login is valid, we respond with a single OK for now, while we reuse the template if the login failsto display the same form but with an error.

Redirections

In some cases, like route refactoring or forms, we will want to perform redirections (either temporary or permanent).In this case, we want to temporarily redirect to the homepage upon successful login, instead of replying with plain text.

Original:Change:
  1. call.respondText("OK")
  1. call.respondRedirect("/", permanent = false)

Using the Form authentication

To illustrate how to receive POST parameters we have handled the login manually, but we can also use the authenticationfeature with a form provider:

  1. install(Authentication) {
  2. form("login") {
  3. userParamName = "username"
  4. passwordParamName = "password"
  5. challenge = FormAuthChallenge.Unauthorized
  6. validate { credentials -> if (credentials.name == credentials.password) UserIdPrincipal(credentials.name) else null }
  7. }
  8. }
  9. route("/login") {
  10. get {
  11. // ...
  12. }
  13. authenticate("login") {
  14. post {
  15. val principal = call.principal<UserIdPrincipal>()
  16. call.respondRedirect("/", permanent = false)
  17. }
  18. }
  19. }

Sessions

To prevent having to authenticate all the pages, we are going to store the user in a session, and that session willbe propagated to all the pages using a session cookie.

  1. data class MySession(val username: String)
  2. fun Application.module() {
  3. install(Sessions) {
  4. cookie<MySession>("SESSION")
  5. }
  6. routing {
  7. authenticate("login") {
  8. post {
  9. val principal = call.principal<UserIdPrincipal>() ?: error("No principal")
  10. call.sessions.set("SESSION", MySession(principal.name))
  11. call.respondRedirect("/", permanent = false)
  12. }
  13. }
  14. }
  15. }

Inside our pages, we can try to get the session and produce different results:

  1. fun Application.module() {
  2. // ...
  3. get("/") {
  4. val session = call.sessions.get<MySession>()
  5. if (session != null) {
  6. call.respondText("User is logged")
  7. } else {
  8. call.respond(FreeMarkerContent("index.ftl", mapOf("data" to IndexData(listOf(1, 2, 3))), ""))
  9. }
  10. }
  11. }

Using HTML DSL instead of FreeMarker

You can choose to generate HTML directly from the code instead of using a Template Engine.For that you can use the HTML DSL. This DSL doesn’t require installation, but requires an additional artifact (see HTML DSL for details).This artifact provides an extension to respond with HTML blocks:

  1. get("/") {
  2. val data = IndexData(listOf(1, 2, 3))
  3. call.respondHtml {
  4. head {
  5. link(rel = "stylesheet", href = "/static/styles.css")
  6. }
  7. body {
  8. ul {
  9. for (item in data.items) {
  10. li { +"$item" }
  11. }
  12. }
  13. }
  14. }
  15. }

The main benefits of an HTML DSL is that you have full statically typed access to variables and it is thoroughly integratedwith the code base.

The downside of all this is that you have to recompile to change the HTML, and you can’t search complete HTML blocks.But it is lightning fast, and you can use the autoreload feature to recompileon change and reload the relevant JVM classes.

Exercises

Exercise 1

Make a registration page and store the user/password datasource in memory in a hashmap.

Exercise 2

Use a database to store the users.