6.21 HTTP Filters
The Micronaut HTTP server supports the ability to apply filters to request/response processing in a similar, but reactive, way to Servlet filters in traditional Java applications.
Filters provide the ability to 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’s 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 with the final entry in the chain being the matched route. The ServerFilterChain.proceed(io.micronaut.http.HttpRequest) method can be used to resume processing of the request.
The proceed(..)
method returns a Reactive Streams Publisher that emits the response that will be returned to the client. Implementors of filters can subscribe to the Publisher and mutate the emitted MutableHttpResponse object to modify the response prior to returning the response to the client.
To put these concepts into practise lets look at an example.
Filters execute in the event loop therefore blocking operations must be offloaded to another thread pool. |