Start United States USA — software Spring WebFlux: Writing Filters

Spring WebFlux: Writing Filters

480
0
TEILEN

Spring WebFlux’s approaches to creating filters involve both WebFilters HandlerFilterFunctions, depending on your use case. See how to use both of them.
Spring WebFlux is the new reactive web framework available as part of Spring 5+. The way filters were written in a traditional Spring MVC based application ( Servlet Filter, HandlerInterceptor) is very different from the way a filter is written in a Spring WebFlux-based application, and this post will briefly go over the WebFlux approach to Filters.
The first approach using WebFilter broadly affects all endpoints and covers WebFlux endpoints written in a functional style as well the endpoints that are written using an annotation style. A WebFilter in Kotlin look like this:
The WebFilter adds a request attribute with the value being a collection where the filter is just putting in a message that it has intercepted the request.
The second approach is more focused and covers only endpoints written using functional style. Here, specific RouterFunctions can be hooked up with a filter, along the following lines.
Consider a Spring WebFlux endpoint defined the following way:
A HandlerFilterFunction that intercepts these APIs alone can be added in a highly focused way along these lines:
Note that there is no need to be explicit about the types in Kotlin — I have added it just to be clear about the types in some of the lambda expressions.
The WebFilter approach and the HandlerFilterFunction are very different from the Spring-WebMVC-based approach of writing filters using Servlet Specs or using HandlerInterceptors. This post summarizes the new approaches. For more information, I have samples available in my git repo, which goes over these in more detail.

Continue reading...