Building a simple Vert-x application

Vert.x is a powerful toolkit for building reactive, event-driven applications on the Java Virtual Machine (JVM). It provides an asynchronous, non-blocking programming model that allows you to handle high concurrency with ease.

In this tutorial, we will walk through the process of creating a basic Vert.x application from scratch. We’ll cover the essential concepts and components of Vert.x, including creating an HTTP server, defining routes, handling requests, and serving static files. By the end of this tutorial, you will have a solid foundation for building more complex and scalable applications with Vert.x.

Getting started with Vert.x

Here is the list of topics we will cover in this article:

  1. Setting up the Development Environment: We’ll start by setting up our development environment by installing the necessary tools and dependencies, including Java and Vert.x.
  2. Creating a Basic HTTP Server: We’ll create a simple Vert.x application that sets up an HTTP server and listens for incoming requests.
  3. Defining Routes and Handling Requests: We’ll define routes for different URLs and implement request handlers to process the incoming requests.
  4. Handling Request Parameters: We’ll explore how to handle request parameters, such as query parameters and path variables, and incorporate them into our application logic.
  5. Serving Static Files: We’ll learn how to serve static files, such as HTML, CSS, and JavaScript, using the built-in StaticHandler in Vert.x.

Let’s get started!

A simple Vert.x example

For our simple example, we will use JBang as scripting language. You can learn more about JBang in this article: JBang: Create Java scripts like a pro

If you prefer using Maven or Gradle to run our example simple add the dependencies you can find in the JBang comments (//DEPS) into your configuration file.

Here is our Vert.x example:

///usr/bin/env jbang "$0" "$@" ; exit $0
//DEPS io.vertx:vertx-core:4.4.4
//DEPS io.vertx:vertx-web:4.4.4

import io.vertx.core.Vertx;
import io.vertx.core.http.HttpHeaders;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.ext.web.handler.StaticHandler;

public class SimpleVertxApp {

    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();
        Router router = Router.router(vertx);

        // Enable reading request bodies
        router.route().handler(BodyHandler.create());

        // API routes
        router.get("/hello").handler(routingContext -> {
            String name = routingContext.request().getParam("name");
            if (name == null || name.isEmpty()) {
                name = "World";
            }
            String message = "Hello, " + name + "!";
            routingContext.response()
                    .putHeader(HttpHeaders.CONTENT_TYPE, "text/plain")
                    .end(message);
        });

        // Serve static files from the "public" directory
        router.route().handler(StaticHandler.create().setWebRoot("public"));

        vertx.createHttpServer()
                .requestHandler(router)
                .listen(8080, result -> {
                    if (result.succeeded()) {
                        System.out.println("Server started on port 8080");
                    } else {
                        System.err.println("Failed to start server: " + result.cause());
                    }
                });
    }
}

In this example, we are providing the following features:

  1. Request Parameter: The /hello endpoint now accepts a query parameter name. If the name parameter is provided, it will be used in the response message. Otherwise, it defaults to “World”.
  2. Static File Serving: We’ve added a route that serves static files from a public directory. Any files placed in the public directory will be served by the server. For example, if you have a file named index.html in the public directory, you can access it at http://localhost:8080/index.html.

Focus on the Vert.x API:

Within this example class, we are using some common Vert.x API which allow you to build reactive responses:

  1. Vertx: The Vertx class is the entry point for creating and managing the Vert.x instance. It provides various methods for creating HTTP servers, event buses, timers, and more.
  2. Router: The Router class is responsible for defining and managing the routes for incoming HTTP requests. It allows you to match requests to specific paths, handle request parameters, and define request handlers for different routes.
  3. HttpServer: The HttpServer class represents an HTTP server that listens for incoming requests. It is created using vertx.createHttpServer() and can be configured with request handlers, SSL settings, and other properties.
  4. HttpServerResponse: The HttpServerResponse class represents the server-side response for an HTTP request. It allows you to set response headers, write response bodies, and end the response.
  5. RoutingContext: The RoutingContext class provides context information and various utility methods for handling an individual HTTP request in the router. It allows you to access request parameters, headers, cookies, and the HTTP response.
  6. Handler: In Vert.x, a Handler is a functional interface that represents a unit of work to be executed in response to an event. In the example, we use lambda expressions as request handlers to handle specific routes or events.
  7. BodyHandler: The BodyHandler class is a built-in Vert.x handler that enables reading request bodies. In the example, we use BodyHandler.create() to enable reading request bodies for all routes.
  8. StaticHandler: The StaticHandler class is a built-in Vert.x handler for serving static files from a directory. It automatically maps incoming requests to files in the specified directory and serves them as responses.

Testing our Vert.x application

To test our Vert.x application, you can run it with:

jbang SimpleVertxApp.java

And then, execute a curl:

curl http://localhost:8080/hello
Hello, World!

Much the same way, if you have an available public/test.html page, you can access it via:

curl http://localhost:8080/test.html

Conclusion

Congratulations! You’ve successfully completed the tutorial on building a simple Vert.x application. You’ve learned the fundamental concepts and components of Vert.x, enabling you to develop reactive, event-driven applications with ease.