This article is Part 2 of Javalin 101. It shows the steps to serve a few common type of web content.
JSON responses
-
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.+") } -
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) } -
This gives you a JSON response such as the following.

Static files
-
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) -
Next, create your directory within the application's classpath.

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

Specific Response Code
-
Create an endpoint and specify the status as 404.
app.get("/notfound") { ctx -> ctx.status(404).json(mapOf("message" to "Not found")) } -
This gives you a 404 error with a JSON body.

Secure with Self-Signed Cert
-
Create and enroll self-signed cert.
-
Copy certificate and key to your resources directory

-
Add the Javalin SSL plugin
dependencies { ... implementation("io.javalin.community.ssl:ssl-plugin:6.3.0") } -
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() -
Run and test the application on https.
