Javalin 101 with Kotlin & Gradle

If you already know Kotlin & Gradle and want to develop a simple web application, Javalin is a good option.

This article shows the steps to develop a Javalin application using IntelliJ IDE.


1) Create a new Kotlin project in IntelliJ.

2) Provide a name and select Gradle as the build system.

3) Open the "build.gradle.kts" file once the project is created.

4) Add Javalin into the dependencies.

implementation("io.javalin:javalin:6.3.0")

5) Create a new Kotlin file, with a Main class.

import io.javalin.Javalin

fun main(args: Array<String>) {
    val app = Javalin.create(/*config*/)
        .get("/") { it.result("Hello World") }
        .start(7777)
}

6) Now you have a simple web application that returns a string.

7) But, when you run this code, it gives you an error - "It looks like you don't have a logger in your project". You need to add a logger for the Javalin application to launch.

dependencies {
    // other codes
    implementation("io.javalin:javalin:6.3.0")
    implementation("org.slf4j:slf4j-simple:2.0.16")
}

8) The easiest solution is to use slf4j-simple. Add it to the dependencies block and create a configuration in the main/resources directory.

9) A sample configuration is as follows.

# see https://www.slf4j.org/apidocs/org/slf4j/simple/SimpleLogger.html
org.slf4j.simpleLogger.defaultLogLevel=DEBUG
org.slf4j.simpleLogger.showDateTime=true
org.slf4j.simpleLogger.dateTimeFormat=YYYY-MM-dd HH:mm:ss.SSS
# less jetty noise
org.slf4j.simpleLogger.log.org.eclipse.jetty=INFO
# more javalin noise
org.slf4j.simpleLogger.log.io.javalin=TRACE

10) Finally do a gradle sync and run the Main class. You should see the application is launched successfully.


Try accessing the URL from your browser or the Postman tool. You should see the "Hello World" string printed.

(Browser)

(Postman)


AI Summary
gpt-4o-2024-05-13 2024-09-04 01:32:10
This article provides a step-by-step guide on developing a simple web application using Javalin with Kotlin and Gradle. It covers creating a project in IntelliJ, configuring Gradle dependencies, adding a logger, and running a minimal "Hello World" web app.
Chrome On-device AI 2024-09-19 18:25:40

Share Article