6.23 HTTP Filters
The Micronaut HTTP server supports applying filters to request/response processing in a similar (but reactive) way to Servlet filters in traditional Java applications.
Filters support the following use cases:
Decoration of the incoming HttpRequest
Modification of the outgoing HttpResponse
Implementation of cross-cutting concerns such as security, tracing, etc.
For a server application, the HttpServerFilter interface doFilter
method can be implemented.
The doFilter
method accepts the HttpRequest and an instance of ServerFilterChain.
The ServerFilterChain
interface contains a resolved chain of filters where the final entry in the chain is the matched route. The ServerFilterChain.proceed(io.micronaut.http.HttpRequest) method resumes processing of the request.
The proceed(..)
method returns a Reactive Streams Publisher that emits the response to be returned to the client. Implementors of filters can subscribe to the Publisher and mutate the emitted MutableHttpResponse to modify the response prior to returning the response to the client.
To put these concepts into practice lets look at an example.
Filters execute in the event loop, so blocking operations must be offloaded to another thread pool. |