In traditional Spring MVC filter I can add some code after chain.doFilter
so that they will executed at the very end. For example:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
chain.doFilter(request, response);
A();
}
The function A
will be executed at the very end after all filters and controllers are executed, even after onBeforeCommitResponse
is invoked.
I want to do this same in WebFlux WebFilter
.
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
return chain.filter(exchange);
// Call A() after all filters, controllers and after beforeCommit
}
How do I achieve this?
If you want the logic to be executed after all filters and after controller logic finished, you can do something like this:
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
return chain.filter(exchange).doFinally(signalType -> {
//here signalType.toString() is `onComplete`
System.out.println("After all filters and controller");
// Call A()
});
}
Using this in my sample code, produces the following logs (I have 3 webfilters):
2020-07-23 12:35:02.604 INFO c.b.e.i.ImageServiceApplication :[ ] Starting ImageServiceApplication on in1-1025453mbp with PID 97673 (/Users/Abhi/codes/image-service/out/production/classes started by 1025453 in /Users/Abhi/codes/image-service)
2020-07-23 12:35:02.606 INFO c.b.e.i.ImageServiceApplication :[ ] No active profile set, falling back to default profiles: default
2020-07-23 12:35:04.142 INFO o.s.b.a.e.web.EndpointLinksResolver :[ ] Exposing 2 endpoint(s) beneath base path '/actuator'
2020-07-23 12:35:04.461 INFO o.s.b.web.embedded.netty.NettyWebServer :[ ] Netty started on port(s): 8080
2020-07-23 12:35:04.479 INFO c.b.e.i.ImageServiceApplication :[ ] Started ImageServiceApplication in 2.134 seconds (JVM running for 2.767)
Executing ScopeCheckFilter
Executing TenancyContextFilter
Executing ImageSizeCheckFilter
2020-07-23 12:36:58.267 INFO c.b.e.i.controller.ImageController :[tenant1] Request received to generate SAS Token
2020-07-23 12:36:59.722 INFO c.b.e.i.s.a.AzureImageStorageService :[tenant1] Container exists
2020-07-23 12:36:59.722 INFO c.b.e.i.s.a.AzureImageStorageService :[tenant1] Generating SAS Token
After all filters
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