Web


  • io.vertx.reactivex.core.http`
    • Class HttpServer
  • io.vertx.ext.web
    • Interface Router

HttpServer

Vert.x-Web uses and exposes the API from Vert.x core. Here’s a hello world web server written using Vert.x core. At this point there is no Vert.x-Web involved:

HttpServer server = vertx.createHttpServer();

server.requestHandler(request -> {

  // This handler gets called for each request that arrives on the server
  HttpServerResponse response = request.response();
  response.putHeader("content-type", "text/plain");

  // Write to the response and end it
  response.end("Hello World!");
});

server.listen(8080);

Routing by exact path

A route can be set-up to match the path from the request URI. In this case it will match any request which has a path that’s the same as the specified path.

Route route = router.route().path("/some/path/");

route.handler(ctx -> {
  // This handler will be called for the following request paths:

  // `/some/path/`
  // `/some/path//`
  //
  // but not:
  // `/some/path` the end slash in the path makes it strict
  // `/some/path/subdir`
});

// paths that do not end with slash are not strict
// this means that the trailing slash is optional
// and they match regardless
Route route2 = router.route().path("/some/path");

route2.handler(ctx -> {
  // This handler will be called for the following request paths:

  // `/some/path`
  // `/some/path/`
  // `/some/path//`
  //
  // but not:
  // `/some/path/subdir`
});

Routing by paths that begin with something

Route route = router.route().path("/some/path/*");

route.handler(ctx -> {
  // This handler will be called for any path that starts with
  // `/some/path/`, e.g.

  // `/some/path/`
  // `/some/path/subdir`
  // `/some/path/subdir/blah.html`
  //
  // but **ALSO**:
  // `/some/path` the final slash is always optional with a wildcard to preserve
  //              compatibility with many client libraries.
  // but **NOT**:
  // `/some/patha`
  // `/some/patha/`
  // etc...
});

Capturing path parameters

router
  .route(HttpMethod.POST, "/catalogue/products/:productType/:productID/")
  .handler(ctx -> {

    String productType = ctx.pathParam("productType");
    String productID = ctx.pathParam("productID");

    // Do something with them...
  });

For more on routing see: https://vertx.io/docs/vertx-web/java/#_routing_by_http_method

Example

   public class ProductVerticle extends AbstractVerticle {

        @Override
        public void start(Promise<Void> startPromise) throws Exception {
            vertx.createHttpServer(new HttpServerOptions())
                    .requestHandler(getRouter())
                    .listen(8080,asyncResult -> {
                        if (asyncResult.succeeded()) {
                            System.out.println("ProductVerticle SUCCESS");
                            startPromise.complete();
                        } else {
                            System.out.println("ProductVerticle FAILED");
                            startPromise.fail(asyncResult.cause());
                        }
                    });
        }

        private Router getRouter() throws FileNotFoundException {
            Router router = Router.router(vertx);

            // call API and place message in MQ after completion
            router.post("/product").handler(this::createProductRecAndplaceMessageInMq);

            // GET request
            router.get("/product").handler(handler -> handler.response().end("all Product details "));

            // GET request with path parameters
            router.get("/product/:name").handler(handler -> {
                String name = handler.pathParam("name");
                handler.response().end(String.format("Product %s details ", name));
            });

            // Get reroute
            router.get("/producer").handler(a -> {
                a.reroute("/subproducer");
            });
            router.get("/subproducer").handler( i-> i.response().end("Hello subproducer"));

            // POST request
            router.post("/mail").handler(context -> {
                context.request().bodyHandler(System.out::println);
                context.response().end("done");
            });

            return router;
        }

        private void createProductRecAndplaceMessageInMq(RoutingContext ctx) {
            //  perform API call task...
            vertx.eventBus().request("mqHandlerOnAPICompletion","", reply -> ctx.request().response().end((String) "Created product record. Placing message in MQ: " + reply.result().body()));
        }
}
Complete code: http://jreact.com/index.php/2023/12/23/vertx-httpserver-router/