I am looking for servlet Filter
equivalent in Spring WebFlux. The WebFilter
seems to only fires before the controller but not after. e.g I can add a WebFilter
to do something when a request comes in, but I couldn't find an equivalent "filter" to do something when a response is sending back.
Can you have a "filter" that fires in both ways?
CodePudding user response:
You can still use WebFilter
to modify your server's outbound responses as well. Here's an example of adding a header to the response:
@Component
public class ExampleWebFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange serverWebExchange,
WebFilterChain webFilterChain) {
serverWebExchange.getResponse()
.getHeaders().add("web-filter", "web-filter-test");
return webFilterChain.filter(serverWebExchange);
}
}
Reference: https://www.baeldung.com/spring-webflux-filters
CodePudding user response:
Just add code after the webFilterChain.filter
call.
@Component
public class MyFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
Mono<Void> result = chain.filter(exchange);
return result.then(<do-whatever>);
}