Vertx-web – Sample Application


Vert.x-Web is a set of building blocks for building web applications with Vert.x. Vert.x-Web can be used to create classic server-side web applications, RESTful web applications, ‘real-time’ (server push) web applications, or any other kind of web application. Vert.x-Web is a great fit for writing RESTful HTTP micro-services. In this post, we will discuss about writing a developing a basic rest api using vert.x-web.

Here is the sample API using Vert.x-Web:

package com.malliktalksjava.vertx.samples;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.Router;

public class MainVerticle extends AbstractVerticle {

  @Override
  public void start(Promise<Void> startPromise) throws Exception {
    HttpServer server = vertx.createHttpServer();
    Router router = Router.router(vertx);

    router.route().handler(ctx -> {

      // This handler will be called for every request
      HttpServerResponse response = ctx.response();
      response.putHeader("content-type", "application/json");

      // Write to the response and end it
      response.end("Hello from Vert.x-Web!" );
    });

    server.requestHandler(router).listen(8888);
  }
}

Create an HTTP server as before, then create a router. Then create a simple route with no matching criteria so it will match all requests that arrive on the server.
Then specify a handler for that route. That handler will be called for all requests that arrive on the server.
The object that gets passed into the handler is a RoutingContext – this contains the standard Vert.x HttpServerRequest and HttpServerResponse but also various other useful stuff that makes working with Vert.x-Web simpler.
For every request that is routed there is a unique routing context instance, and the same instance is passed to all handlers for that request.
Once the handler is setup, set the request handler of the HTTP server to pass all incoming requests to handle.

Try to access the application on using http://localhost:8888. Here is the output:

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.