I am trying to make an application in spring webflux. But there is a lot of stuff that I can't find in the documentation.
I have a webfilter where I want to add a wrapper around the response. Example:
Reponse before:
{
"id": 1,
"name": "asdf"
}
Response after:
{
"status": "success",
"data": {
"id": 1,
"name": "asdf"
}
}
This is the WebFilter at the moment:
@Component
public class ResponseWrapperFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
// Add wrapper to the response content...
return webFilterChain.filter(serverWebExchange);
}
}
But I can't find a way to get or edit the body of the response.
How can I change the response output in a WebFilter
?
As stated in the javadoc, WebFilter
is made for application-agnostic, cross-cutting concerns. WebFilters
usually mutate the request headers, add attributes to the exchange or handle the response altogether without delegating to the rest of the chain.
I don't think that what you're trying to achieve is easily doable or even something that should be achieved this way. At the raw exchange level, you're dealing with a Flux<DataBuffer>
, which is the response body split randomly in groups of bytes.
You could somehow wrap the response in a filter and use Flux.concat
to prepend and append data to the actual response written by the handler. But there are a lot of questions regarding encoding, infinite streams, etc.
Maybe this is a concern that should be achieved at the Encoder
level, since there you could restrict that behavior to a particular media type.
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