Javalin is a web and microservice framework designed for Java 8 (and onwards versions) and Kotlin. Started just with a fork of Sparkjava, it later turned into a completely independent web framework. Javalin became the most talked-about Java framework for its simplicity, flexibility, and being lightweight.
Table of Contents
In this article, we will be looking into Javalin, its notable features, it’s working, and why it can be an ideal choice for a Java web framework for a developer.
The first stable public of Javalin was released way back in 2017, upon its release, it got in the limelight for being an extremely lightweight web framework available out there. It also received a favoring response from the Java community.
The developers behind Javalin wrote the whole framework in Kotlin. Their primary focus has always been on providing simplicity, flexibility, and interoperability. They have built the framework on top of Jetty, ensuring that the performance must be as same as possible to raw Jetty code. The users are also not required to use any @annotations, there is no need to extend any class or to download different versions of Javalin. Other than being lightweight and simple, it also offered all the new and popular features as it supports HTTP2, WebSockets, and async requests. You can also use it to build RESTful Web Service applications. As it uses the embedded Jetty server, it can smoothly run the RESTful applications.
As mentioned earlier, Java developers do not need to use @annotations or to extend any class, it only requires importing the following library,
import io.javalin.Javalin;
and then you can start your code with a public static void main. This makes it a suitable option for students and new developers as a complicated setup of a framework can be an overwhelming experience for them.
Javalin comes with a Jetty embedded server, so it does not require any third-party server to run an application. You just have to add the dependency and write a single line of code to create and start a server. This is how you can do that,
1. import io.javalin.Javalin; 2. public class DemoApp 3. { 4. public static void main(String[] args) 5. { 6. Javalin app = Javalin.create().start(5000); // creating and launching the server 7. app.get("/", ctx -> ctx.result("1 2 3 Start.")); // adding root endpoint 8. } 9. }
This is a great option as it allows the developers to focus on the classes and algorithms instead of working on the settings to configure an application server.
Javalin offers an extensive range of options for configuring the framework as per your requirements. The code shown below demonstrates the basic configuration for the Javalin framework before starting the development process,
1. var demoApp = Javalin.create(config -> 2. { 3. config.defaultContentType = "application/json"; 4. config.addStaticFiles("/public"); 5. config.asyncRequestTimeout = 5_000L; 6. config.autogenerateEtags = true; 7. config.dynamicGzip = true; 8. config.enforceSsl = true; 9. }).routes(() -> 10. { 11. path("users", () -> 12. { 13. get(UserController::getAll); 14. post(UserController::create); 15. path(":user-id"(() -> 16. { 17. get(UserController::getOne); 18. patch(UserController::update); 19. delete(UserController::delete); 20. }); 21. ws("events", userController::webSocketEvents); 22. }); 23. }).start(port);
It is also very straightforward to validate the parameters in Javalin. For instance, See the path params, query params, and form params validation code snippet below,
1. var1 myQpStr = ctx.queryParam("queryParam"); //Returns a string or null, no validation 2. var1 myQpInt = ctx.pathParam("queryParam", Integer.class).get(); // Returns an integer 3. var1 myQpInt = ctx.formParam("queryParam ", Integer.class).check(i -> i > 5).get(); // Integer > 5 4. 5. // This shows validation of a json body: 6. var1 myObj = ctx.bodyValidator(MyObj.class) 7. .check(obj -> obj.myObjectProperty == someValue) 8. .get(); 9. // This shows the validation of two dependent query parameters: 10. var1 starting = ctx.queryParam("from", Instant.class).get(); 11. var1 ending = ctx.queryParam("to", Instant.class) 12. .check(it -> it.isAfter(starting), "'to' must come 'from'") 13. .get();
Like some other web frameworks, Handlers also exists in Javalin. Javalin offers the following handlers,
See their demonstration below,
1. //examples for before handlers 2. 3. // - it will run before all requests 4. demoApp.before(ctx -> { 5. }); 6. 7. // - It will run before request to /path/* 8. demoApp.before("/path/*", ctx -> { 9. }); 10. 11. 12. //examples for endpoint handlers 13. demoApp.get("/", ctx -> 14. { 15. // lines of code will be placed. 16. ctx.json(obj); 17. }); 18. demoApp.get("/hello/*", ctx -> 19. { 20. // capture all the requests to sub-paths of /hello/ 21. }); 22. 23. //after handlers 24. demoApp.after (ctx -> 25. { 26. // run after all requests 27. }); 28. demoApp.after ("/path/*", ctx -> 29. { 30. // runs after request to /path/* 31. });
For dealing with authentication and authorization, Javalin has a functional interface called, AccessManager which allows developers to implement their own access manager.
1. // Setting the access-manager 2. demoApp.accessManager((handler, ctx, permittedRoles) -> 3. { 4. MyRole myRole = getUserRole(ctx); 5. if (permittedRoles.contains(myRole)) 6. { 7. handler.handle(ctx); 8. } else 9. { 10. ctx.status(401).result("Not authorized"); 11. } 12. }); 13. 14. Role getUserRole(Context ctx) 15. { 16. // The user role will be determined based on the request. 17. } 18. 19. enum MyRole implements Role 20. { 21. ANYONE, ROLE_ONE, ROLE_TWO, ROLE_THREE; 22. } 23. 24. demoApp.routes(() -> 25. { 26. get("/Not secured", ctx -> ctx.result("Hello World"), roles(ANYONE)); 27. get("/secured", ctx -> ctx.result("Hello World"), roles(ROLE_ONE)); 28. });
These were some of the functionalities by Javalin to get familiarized with the framework.
To deploy a Javalin application, you just need to create a jar file with dependencies using maven-assembly-plugin, then you can launch the jar file with this line of code,
java -jar filename.jar
Javalin got its share of popularity due to being extremely lightweight. Along with being a web framework, it can also be used as a microservice framework. Javalin is a simple and unopinionated framework, which makes it a good option if you need to get started quickly. It has a relatively transparent layer, which helps the developer in understanding what is going on behind the code.
The built-in application server is also a significant distinguishing factor in Javalin. Javalin also works well with GraalVM and it produces a small final binary of around 22 MB in size. The API for Javalin is also built while keeping discoverability in mind. The server configuration object has a fluent and chainable API. The context object also offers everything required to handle an HTTP request.
Javalin also makes it easier to write API-based applications with minimum overhead. The developer also gets complete access to the JVM threading power and asynchronous calls with Javalin. It also allows the use of all the existing Java libraries, making it a good option for your standard Java environment. The driven developers behind Javalin have also been releasing a new backward-compatible release every month since the first version of the framework. The pull requests and issues are also reviewed, very frequently.
Although there are many Java web frameworks available that offer similar functionalities but they either require a lot of setups even for developing a simple API, they produce a relatively heavier binary, or more often the frameworks are quite heavyweight making them sluggish. Javalin offers such a unique combination that makes it significantly faster than almost every heavier framework and even many lightweight frameworks.
Javalin also offers a dedicated page for educators on its website. As stated on their website, the idea behind this page is that it is a source of documentation and tutorials on Javalin for students and educators. Along with that, it is presented as a better choice of framework for prototyping and demos as it saves time and effort usually taken for configuring and setting the application server which can be utilized elsewhere. This page could be a great place to get to know more about Javalin and explore its further applications.
This was just a brief overview of the features by Javalin. Although the scope of Javalin is limited to the web layer, it offers everything that is required to develop a simple web application. It is well suited for both commercial and personal projects due to being a fast and lightweight framework.
You can further explore to find out more applications of Javalin such as how you can run it on GraalVM. More details can be easily found on the official documentation page of Javalin and on various Java forums.
Also Read: An Introduction To Inline Classes In Java
Full Stack Java Developer | Writer | Recruiter, bridging the gap between exceptional talent and opportunities, for some of the biggest Fortune 500 companies.
Create a free profile and find your next great opportunity.
Sign up and find a perfect match for your team.
Xperti vets skilled professionals with its unique talent-matching process.
Connect and engage with technology enthusiasts.
© Xperti.io All Rights Reserved
Privacy
Terms of use