Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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?
–
–
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
–
–
–
–
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>);
–
–
–
–
I think the trick you are looking for is when you call the filter chain in the filter method you want the following
@Override
public Mono<Void> filter(@NonNull final ServerWebExchange exchange, @NonNull final WebFilterChain chain) {
final ServerHttpRequest request = exchange.getRequest();
final String requestUrl = request.getURI().toString();
// preRequest: - YOUR LOGIC
return chain.filter(exchange).doFinally(signalType -> {
/* This doFinally is included so the tests will pass */
log.info("postHandle: Just like an interceptor");
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.