Using HandlerFilterFunction

We will implement a new HandlerFilterFunction, SampleHandlerFilterFunction, in which we will look at a path variable (pathVariable) and check for its value. If the value is equal to value2, we will mark the status as BAD_REQUEST. It's important to note that since HandlerFilterFunction applies only to functional-based, even though the path variable value is equal to value2, the status is not stamped as BAD_REQUEST, and the response received is OK:

public class SampleHandlerFilterFunction implements 
HandlerFilterFunction<ServerResponse, ServerResponse> {
@Override
public Mono<ServerResponse> filter(ServerRequest serverRequest,
HandlerFunction<ServerResponse> handlerFunction) {
if (serverRequest.pathVariable("pathVariable")
.equalsIgnoreCase("value2")) {
return ServerResponse.status(BAD_REQUEST).build();
}
return handlerFunction.handle(serverRequest);
}
}

SampleHandlerFilterFunction implements the HandlerFilterFunction class, and also implements the filter method. In this class, we will explicitly set the response status as a bad request, if a condition is met:

@Test
public void filtertest1_with_pathVariable_equalTo_value2_apply_HandlerFilterFunction() {
webTestClient.get().uri("/filtertest1/value2")
.exchange()
.expectStatus().isOk();
}
@Test
public void filtertest2_with_pathVariable_equalTo_value2_apply_HandlerFilterFunction() {
webTestClient.get().uri("/filtertest2/value2")
.exchange()
.expectStatus().isBadRequest();
}

In the preceding test cases, the path tested is different, and since HandlerFilterFunction applies only to functional-based, the response is OK when the path is filtertest1, and it's BAD_REQUEST when the path is filtertest2.

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

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