Javalin Part 2

This article is Part 2 of Javalin 101. It shows the steps to serve a few common type of web content.

JSON responses

1) To render JSON response, we need to serial/deserialize Kotlin object. There are a few options, such as Jackson.

dependencies {
   ...
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.17.+")
}

2) A list of objects can be constructed using "listof" and "mapOf".

app.get("/promotions") { ctx ->
        val promotions = listOf(
            mapOf(
                "name" to "Promo 1",
                "description" to "Promo 1 description",
                "discount" to 10
            ),
            mapOf(
                "name" to "Promo 2",
                "description" to "Promo 2 description",
                "discount" to 20
            )
        )
        ctx.json(promotions)
    }

3) This gives you a JSON response such as the following.

Static files

1) Some configuration must be added to serve static files, including the directory and location.

val app = Javalin.create { config ->
        config.staticFiles.add { staticFiles -> {
                staticFiles.directory = "/public"
                staticFiles.location = Location.CLASSPATH
            }
        }
    }.start(7777)

2) Next, create your directory within the application's classpath.

3) Place the static file into the directory and try to access the URL.

Specific Response Code

1) Create an endpoint and specify the status as 404.

app.get("/notfound") { ctx -> ctx.status(404).json(mapOf("message" to "Not found")) }

2) This gives you a 404 error with a JSON body.

Secure with Self-Signed Cert

1) Create and enroll self-signed cert.

2) Copy certificate and key to your resources directory

3) Add the Javalin SSL plugin

dependencies {
   ...
    implementation("io.javalin.community.ssl:ssl-plugin:6.3.0")
}

4) Register the plugin with cert

    val app = Javalin.create { config ->
        config.staticFiles.add { staticFiles -> {
                staticFiles.directory = "/public"
                staticFiles.location = Location.CLASSPATH
            }
        }
        config.registerPlugin(SslPlugin{ sslConfig ->
            sslConfig.pemFromClasspath(
                "certs/certificate.pem",
                "certs/key.pem",
                null
            )
        })
    }.start()

5) Run and test the application on https.


AI Summary
gpt-4o-2024-05-13 2024-09-06 00:43:44
This article, part of the Javalin 101 series, outlines steps for rendering JSON responses, serving static files, setting specific response codes, and securing a Javalin application with a self-signed certificate. It emphasizes configuration and implementation details for each task.
Chrome On-device AI 2024-09-19 19:22:30

Share Article