5

Is it possible to add 2 handlers for a path?

I need to load html contents from a folder and check session values when i access / path.

If i place router.route().handler(StaticHandler.create().setWebRoot("webroot")); it will read contents from webroot folder.

And when i use the following code, It will execute the hanlder code.

router.route("/").handler(routingContext -> {
            Session session = routingContext.session();         
            String name = session.get("uname");
            // some code
        });

But is there any way to execute both handlers when i try to access this path?

I tried

HttpServerResponse response = routingContext.response();
            response.sendFile("webroot/index.html");

But it just read the index.html file and it doesn't read CSS. And I couldn't find a method to read the entire directory.

Adam Michalik
  • 9,678
  • 13
  • 71
  • 102
din_oops
  • 698
  • 1
  • 9
  • 27

2 Answers2

9

Sure you can :)

This is your Verticle i registered two Handlers

@Override
public void start() throws Exception {
    Router router = Router.router(vertx);
    router.route().path("/hello").handler(new Handler0());
    router.route().path("/hello").handler(new Handler1());

    vertx.createHttpServer().requestHandler(router::accept).listen(8080);
}

class Handler0 implements Handler<RoutingContext> {

    @Override
    public void handle(RoutingContext ctx) {
        ctx.put("hi", "your nice");
        ctx.next(); // IMPORTANT!!
    }
}

class Handler1 implements Handler<RoutingContext> {

    @Override
    public void handle(RoutingContext ctx) {
        String hi = ctx.get("hi");
        if (hi.equals("your nice") {
           ctx.request().response().end(hi);
        } else {
           ctx.fail(401); 
        }
    }
}

The ctx.next() calls the next Handler for error handling use ctx.fail

hope this helps :)

Simi
  • 174
  • 1
  • 7
3

Just as the previous comment says you can register multiple handlers. The problem is that the StaticHandler ends the response, so the next handler won't be called by ctx.next().

The solution is to register your handlers before the StaticHandler.

cy3er
  • 1,699
  • 11
  • 14