Interface Middleware
- Functional Interface:
- This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.
RequestHandler.
Middleware is composed once at registration time and stored as a pre-built handler chain inside the router's state machine. There is zero runtime overhead: no lists are visited, no lookups performed, and no objects allocated on the request hot-path.
Middleware is intentionally stateless — it can read Request,
write to Response, and decide whether to call next or
short-circuit. Shared state between layers belongs in HDI handler chains, not here.
// Inline definition — pure lambda, no wrapper types needed
Middleware auth = next -> (req, res) -> {
if (req.header("Authorization") == null) { res.status(401); return null; }
return next.handle(req, res);
};
// Named reusable chain — composed into a single object at call time
Middleware secured = Middleware.of(cors, auth, rateLimit);
// Router-level: applied to every handler registered on this router
AbstractRouter api = new MyRouter(cors, auth);
// Handler-level: applied only to this route
app.get("/admin", (req, res) -> "secret", auth);
app.get("/log", handler, logging, auth);
-
Method Summary
Modifier and TypeMethodDescriptionstatic Middlewareof(Middleware... chain) Composes an ordered chain of middlewares into a singleMiddleware.wrap(RequestHandler next) Wrapsnextwith this middleware's logic.
-
Method Details
-
wrap
Wrapsnextwith this middleware's logic. Called once at boot time during handler registration. Returns aSimpleHandler.FunctionalHandlerlambda — no wrapper types required at the call site.The returned functional handler is boxed into a
SimpleHandlerinternally byAbstractRouter; callers never need to do this manually. -
of
Composes an ordered chain of middlewares into a singleMiddleware. The first element is the outermost wrapper and therefore executes first.The composition loop runs once when
wrap(dev.relism.flash.models.RequestHandler)is called (i.e. at registration time), not at construction of the chain. Zero allocations on the hot-path.Middleware secured = Middleware.of(cors, auth, rateLimit); // execution order: cors → auth → rateLimit → handler
-