I'm trying to solve this: How to rewrite URLs with Spring (Boot) via REST Controllers? by creating some kind of "filter" which would be applied to every incoming HTTP request.
The matter is covered by some answers like for this question: Spring Boot Adding Http Request Interceptors
but interface HandlerInterceptor
deals with javax' HttpServletRequest
and HttpServletResponse
which are not as practical as the new class introduced by Spring i.e. the ServerWebExchange
(see the use of setLocation()
in the code below) which appears in an interface whose name sounds promising, org.springframework.web.server.WebFilter
:
So I ended with something like:
@Component
public class LegacyRestRedirectWebFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
URI origin = exchange.getRequest().getURI();
String path = origin.getPath();
if (path.startsWith("/api/")) {
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
URI location = UriComponentsBuilder.fromUri(origin).replacePath(path.replaceFirst("/api/", "/rest/")).build().toUri();
response.getHeaders().setLocation(location);
}
return chain.filter(exchange);
}
}
...in the same way people are doing something similar like:
Alas, my filter is never called!!!
The thing is: I am not in a "WebFlux" context (on the contrary to the questions above) because:
- I don't need to, and
- I tried and got the following problems:
Reactive Webfilter is not working when we have spring-boot-starter-web dependency in classpath (but no definitive answer); marked duplicate of: Don't spring-boot-starter-web and spring-boot-starter-webflux work together?
Spring WebFlux with traditional Web Security (I have the "traditional"
spring-boot-starter-security
dependency in mypom.xml
plus a@Configuration
class extendingWebSecurityConfigurerAdapter
- but not willing to migrate it to... what by the way?)
Also I don't understand why would I need to be in a WebFlux context, because org.springframework.web.server.WebFilter
neither deals with reactive
nor Webflux
, right? ..or does it? This is not very clear in the Javadoc.
Filter
baeldung.com/spring-boot-add-filter without seing your pom.xml/gradle its hard know what type of application you have. – Toerktumlarespring-web-5.1.9.RELEASE.jar
?! – maxxymeFilter
but after a quick search (albeit the Baeldung not specifying which Filter it is...) I found out this is thejavax.servlet.Filter
and as I said above, I'll try to avoid working with this as it's pure "javax" code and it deals with (Http)ServletRequest/(Http)ServletResponse, [see the casts inRequestResponseLoggingFilter
]. – maxxymeWebClient
. Hence the default, you on the other hand, want to be usingWebFilter
since you want to build a webflux application. And your problem is that you are pulling in things that does not support webflux (springfox v2.9.2) so springfox is probably forcing your app to start as a web app. – Toerktumlare