Using WebFilter

We will be building on top of our project, spring-boot-webflux. To make it isolated from other projects, we will create a new project, spring-boot-webflux-custom. As indicated previously, using WebFilter applies to both annotation-based and functional-based WebFlux approaches. In our example, we'll have two paths: filtertest1 and filtertest2. We will write test cases using WebFluxTestClient, and will assert certain conditions. Being separate from the rest, we will create a new routing config, a handler, and an entirely new REST controller. We will not go into detail on some of the aspects already covered. In this section, we will just go through the WebFilter code, and also some important aspects of the test cases:

@Component
public class SampleWebFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange serverWebExchange,
WebFilterChain webFilterChain) {
serverWebExchange.getResponse().getHeaders().add("filter-added-header",
"filter-added-header-value");
return webFilterChain.filter(serverWebExchange);
}
}

The SampleWebFilter class implements WebFilter, and also implements the filter method. In this class, we will add a new response header, filter-added-header:

@Test
public void filtertest1_with_pathVariable_equalTo_value1_apply_WebFilter() {
EntityExchangeResult<String> result =
webTestClient.get().uri("/filtertest1/value1")
.exchange()
.expectStatus().isOk()
.expectBody(String.class)
.returnResult();
Assert.assertEquals(result.getResponseBody(), "value1");
Assert.assertEquals(result.getResponseHeaders()
.getFirst("filter-added-header"), "filter-added-header-value");
}
@Test
public void filtertest2_with_pathVariable_equalTo_value1_apply_WebFilter() {
EntityExchangeResult<String> result =
webTestClient.get().uri("/filtertest2/value1")
.exchange()
.expectStatus().isOk()
.expectBody(String.class)
.returnResult();
Assert.assertEquals(result.getResponseBody(), "value1");
Assert.assertEquals(result.getResponseHeaders()
.getFirst("filter-added-header"), "filter-added-header-value");
}

In both test cases, for both paths, we will check for newly added headers. When you run the test cases (using mvn test), it will confirm this finding.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.52.33