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:
Javalin dependency is as follows:
1 2 3 4 5 6 7 8 9 10 |
<dependency> <groupId>io.javalin</groupId> <artifactId>javalin</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.7.26</version> </dependency> |
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:
1 2 3 4 5 6 7 8 9 |
package com.huongdanjava.javalin; public class JavalinHelloworld { public static void main(String[] args) { } } |
To work with Javalin, the first thing you need to do is create an instance of the Javalin class:
1 |
Javalin javalin = Javalin.create(); |
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:
1 |
javalin.port(8080); |
If you don’t do this, port random will be assigned when we run the application.
Then start it:
1 |
javalin.start(); |
You can combine all of the above steps using Javalin’s start() method as follows:
1 |
Javalin javalin = Javalin.create().start(8080); |
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:
1 2 3 4 5 6 7 |
javalin.get("/hello", new Handler() { @Override public void handle(Context ctx) throws Exception { ctx.result("Hello World!"); } }); |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package com.huongdanjava.javalin; import io.javalin.Javalin; public class JavalinHelloworld { public static void main(String[] args) { Javalin javalin = Javalin.create().start(8080); javalin.get("/hello", ctx -> ctx.result("Hello World!")); } } |
The result when running the application and request to the address http://localhost:8080/hello as follows:
Very simple, right? With just a few lines of code, we’ve built a RESTful Web Service!