Spring WebFlux Filters
Last Updated :
05 Mar, 2024
In Spring WebFlux, the filters are used to do modifications like it modifies the requests and responses going through the server. This Filter allows us to do basic tasks like modifying headers, logging, authentication etc. In Spring WebFlux Filters, filters are created using WebFilter interface and @WebFilter annotation.
Implementation of WebFlux Filters
public interface WebFilter {
Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain);
}
Step-by-Step Implementation of Spring WebFlux Filters
Below are the steps to implement Spring Webflux Filters.
Step 1: Add Maven Dependency
First, let us define the Maven dependency for WebFlux:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
Step 2: Create an Endpoint
We need to construct a few endpoints. Annotation-based and functional-based methods, one for each. The annotation-based controller will be discussed first:
// Define a Spring WebFlux controller endpoint for handling GET requests with a path variable
@GetMapping(path = "/authors/{name}")
// Method to retrieve and return a Mono<String> representing the provided path variable "name"
public Mono<String> getName(@PathVariable String name) {
// Return a Mono<String> containing the value of the provided path variable "name"
return Mono.just(name);
}
Step 3: Create functional Endpoint
We must construct a handler for the functional endpoint:
Java
@Component
public class AuthorHandler {
public Mono<ServerResponse> getName(ServerRequest request) {
Mono<String> name = Mono.just(request.pathVariable( "name" ));
return ServerResponse.ok().body(name, String. class );
}
}
|
Step 4: WebFlux Routing Function
To achieve the same endpoint, using the Functional Web Framework, we can build a Functional Router. The Routing Function that we are developing here has a Handler Function attached to it.
Java
@Bean
public RouterFunction<ServerResponse> getAuthorRoute() {
return route(GET( "/authors/{id}" ),
request -> ok().body(service
.getAuthor(request.pathVariable( "id" )), Author. class )
);
}
|
Step 5: Add a new header to the response
Apply a WebFilter to the response in order to append a new header. This means that every response behaves like this:
Java
@Component
public class SecondWebFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
serverWebExchange.getResponse().getHeaders().add( "web-filter" , "web-filter-test" );
return webFilterChain.filter(serverWebExchange);
}
}
|
Step 6: Create HandlerFilterFunction
Create a logic that, in the event that the “name” argument equals “article” sets the HTTP status to OK.
Java
public class SecondHandlerFilterFunction
implements HandlerFilterFunction<ServerResponse, ServerResponse> {
@Override
public Mono<ServerResponse> filter(ServerRequest serverRequest,
HandlerFunction<ServerResponse> handlerFunction) {
if (serverRequest.pathVariable( "name" ).equalsIgnoreCase( "article" )) {
return ServerResponse.status(HttpStatus.OK).build();
}
return handlerFunction.handle(serverRequest);
}
}
|
- In this case, we built up a mechanism to set the HTTP status to OK if the value of the “name” field is “article”.
- It is possible to filter handler functions in a reactive web application by using the ExampleHandlerFilterFunction class, which implements HandlerFilterFunction.
- If “article” is present in the “name” path variable, the filter method verifies it and provides a 200 status code along with a Ok response.
- The purpose of this filter is to intercept and alter the response prior to it reaching the handler function, based on predetermined criteria.
Step 7: Test the WebTestClient
The WebTestClient in the WebFlux Framework provides a simple method for testing our filters. We can test HTTP requests to our endpoints with it.
Annotation-based endpoint:
Java
@Test
public void whenUserNameIsGeeksforgeeks_thenWebFilterIsApplied() {
EntityExchangeResult<String> result = webTestClient.get()
.uri( "/users/geeksforgeeks" )
.exchange()
.expectStatus().isOk()
.expectBody(String. class )
.returnResult();
assertEquals(result.getResponseBody(), "geeksforgeeks" );
assertEquals(result.getResponseHeaders().getFirst( "web-filter" ), "web-filter-test" );
}
@Test
public void whenUserNameIsTest_thenHandlerFilterFunctionIsNotApplied() {
webTestClient.get().uri( "/users/article" )
.exchange()
.expectStatus().isOk();
}
|
Functional endpoint:
Java
@Test
public void whenAuthorNameIsGeeksforgeeks_thenWebFilterIsApplied() {
EntityExchangeResult<String> result = webTestClient.get()
.uri( "/authors/geeksforgeeks" )
.exchange()
.expectStatus().isOk()
.expectBody(String. class )
.returnResult();
assertEquals(result.getResponseBody(), "geeksforgeeks" );
assertEquals(result.getResponseHeaders().getFirst( "web-filter" ), "web-filter-test" );
}
@Test
public void whenAuthorNameIsTest_thenHandlerFilterFunctionIsApplied() {
webTestClient.get().uri( "/authors/article" )
.exchange()
.expectStatus().isOk();
}
|
Spring WebFlux Filters helps guarantee that response material is always consumed and offers a mechanism for encoding to and from higher level objects. The filter method allows us to interface with web requests and perform operations via a ServerWebExchange.
Share your thoughts in the comments
Please Login to comment...