Introduce to the Javalin framework

Javalin is a lightweight web framework that can be used to build RESTful Web Service web applications. It uses the embedded Jetty server so we can run the application easily. In this tutorial, I will show you the basic steps to build a RESTful Web Service application with Javalin!

For example, I will create a Maven project with the following content:

Introduce to the Javalin framework

Javalin dependency is as follows:

We also need to declare slf4j-simple dependency to work with Javalin.

Like Spring Boot applications, we can run Javalin applications using the class with the main() method. I will create a class with main() method as follows:

To work with Javalin, the first thing you need to do is create an instance of the Javalin class:

This object will be created with the web server and then we will add the handler to this web server so that it can handle the request from the user.

You can set the port for the web server:

If you don’t do this, port random will be assigned when we run the application.

Then start it:

You can combine all of the above steps using Javalin’s start() method as follows:

Once you’ve got the Javalin object, you can use get(), post(), put(), delete() methods to implement RESTful APIs with GET, POST, PUT, DELETE. The parameters of these methods will be what is the request URL and a Functional Interface named Handler with the task of implementing the handle request from the user.

For example, now I need to implement a GET “/hello” request for the application. I will code as follows:

Context object in the parameter of handle() method will contain all information about the request and the user’s response. To set the return response for the user, we use the result() method of the Context object. The above code can be shortened to use Lambda Expression (you need to adjust Java Compiler to Java 1.8 to do this) as follows:

The result when running the application and request to the address http://localhost:8080/hello as follows:

Introduce to the Javalin framework

Very simple, right? With just a few lines of code, we’ve built a RESTful Web Service!

Add Comment