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.
This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference. @FunctionalInterface public interface Handler<E> A generic event handler. This interface is used heavily throughout Vert.
Vert. x uses low level IO library Netty. The application framework includes these features: Polyglot.
A router receives request from an HttpServer and routes it to the first matching Route that it contains. A router can contain many routes. Routers are also used for routing failures.
Interface RoutingContext. Represents the context for the handling of a request in Vert. x-Web. A new instance is created for each HTTP request that is received in the Handler.
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 :)
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With